简体   繁体   中英

Pass the argv and argc to thread

My program receives arguments from the user

int main(int argc, char *argv[])

and I have this function inside some thread (I can't change the function):

func(&argc, &argv);

As you can see, I need to call the thread, and inside this thread, to call func with those parameters. I saw that there is a way to sent the thread multiple parameters with struct.

How does the struct suppose to look like? And how do I copy those parameters to the struct?

struct arg_holder {
    int argc;
    char ** argv;
};

void * thread_caller(void * arg) {
    struct arg_holder arg_struct = *(struct arg_holder *)arg;
    free(arg);
    return func(arg_struct->argc, arg_struct->argv);
}

in main :

struct arg_holder * arg_struct = malloc(sizeof(*arg_struct));
arg_struct->argc = argc;
arg_struct->argv = argv;

pthread_create(&thread_id, NULL, thread_caller, arg_struct);

Thought to mention that, AFAIK, you can pass the command line arguments to the thread without copying them (ie - create a dedicated struct which contain them using malloc), due to the fact that the life time of the command line arguments is the life time of the process (main) they were provided to.

Cheers,

Guy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM