Create pthread with the function of multiple arguments

蹲街弑〆低调 提交于 2020-05-13 06:35:42

问题


If I am going to create a pthread for the following function.

Assume everything is properly delared.

pthread_create(&threadId, &attr, (void * (*)(void*))function, //what should be the arguments for here??);
int a = 0;
int b = 1;
//c and d are global variables.

void function(int a, int b){
    c = a;
    d = b;
}

回答1:


This does not work. function() has to take exactly one argument. That's why you have to do this:

(void * ()(void))

You're telling your compiler "no, seriously, this function only takes one argument", which of course it doesn't.

What you have to do instead is pass a single argument (say a pointer to a struct) which gets you the information you need.

Edit: See here for an example: number of arguments for a function in pthread




回答2:


The pthread thread function always takes one void * argument and returns a void * value. If you want to pass two arguments, you must wrap them in a struct - for example:

struct thread_args {
    int a;
    int b;
};

void *function(void *);

struct thread_args *args = malloc(sizeof *args);

if (args != NULL)
{
    args->a = 0;
    args->b = 1;
    pthread_create(&threadId, &attr, &function, args);
}

and for the thread function itself:

void *function(void *argp)
{
    struct thread_args *args = argp;

    int c = args->a;
    int d = args->b;

    free(args);

    /* ... */

You don't need to use malloc() and free(), but you must somehow ensure that the original thread doesn't deallocate or re-use the thread arguments struct until the called thread has finished with it.



来源:https://stackoverflow.com/questions/19917211/create-pthread-with-the-function-of-multiple-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!