Reputation: 55
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;
}
Upvotes: 4
Views: 13603
Reputation: 239341
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.
Upvotes: 3
Reputation: 929
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
Upvotes: 5