Reputation: 35
I have an example code about thread creation in C. In the part where I create the thread, I don't get what all the void pointers are for, and what do they do.
void* pthread_function(int thread_id) {
pthread_mutex_lock(&mutex);
printf("I'm thread number %d in mutual exclusión\n",thread_id);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(int argc,char** argv) {
// Init mutex
pthread_mutex_init(&mutex,NULL);
// Create threads
pthread_t thread[NUM_THREADS];
long int i;
for (i=0;i<NUM_THREADS;++i) {
pthread_create(thread+i,NULL,(void* (*)(void*))pthread_function (void*)(i));
}
}
How do the pointers work here?
pthread_create(thread+i,NULL,(void* (*)(void*))pthread_function (void*)(i));
Thanks for your help.
Upvotes: 0
Views: 83
Reputation: 12404
A thread function is supposed to have the following signature:
void *thread_func(void *thread_param);
If you have such a function, you can create a thread with it without such a casting mess:
void *thread_func(void *thread_param)
{
printf("Success!\n");
return NULL;
}
...
pthread_t thread_var;
int param = 42;
int result = pthread_create(&thread_var, NULL, thread_func, ¶m);
Unfortunately the thread function in your example does not have the proper signature. Therefore the authore decided not to fix it, but to mess around with weird casts.
The type of the function is (void*(*)(void*))
. The author tries to make wrong ends meet with casting the thread function:
(void* (*)(void*))pthread_function
But then another error is introduced: Not the function address is cast but the function is called and the return value is used for the cast:
pthread_function (void*)(i)
This does not even compile as it is a syntax error. It should probably be
pthread_function((void*)i)
Or it could be meant to be like this:
pthread_create(thread+i,NULL,(void* (*)(void*))pthread_function, (void*)(i));
But as this is all wrong anyway, it doesn't really matter.
You better search again for a correct example for thread creation.
Upvotes: 2