Consider this simple code:
void* threadFunction(void* arg) {
int argument=(int)arg;
printf("%d recieved\n", argument);
return NULL;
}
int main(int argv, char* argc[]) {
int error;
int i=0;
pthread_t thread;
int argument_to_thread=0;
if ((error=pthread_create(&thread, NULL, threadFunction, (void*)argument_to_thread))!=0) {
printf("Can't create thread: [%s]\n", strerror(error));
return 1;
}
pthread_join(thread, NULL);
return 0;
}
This works, but two things bother me here.
First, I want to send more than one argument to threadFunction().
Of course, I can pass a pointer to an array, but what if I want to pass two arguments of different types? (say an int
and char*
) How can it be done?
The second thing that bothers me here, is the warnings I get when compiling the above...
test2.c: In function ‘threadFunction’:
test2.c:8:15: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
int argument=(int)arg;
^
test2.c: In function ‘main’:
test2.c:24:59: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
if ((error=pthread_create(&thread, NULL, threadFunction, (void*)argument_to_thread))!=0) {
^
Now, I can make this go away by doing this:
if ((error=pthread_create(&thread, NULL, threadFunction, (void*)&argument_to_thread))!=0) {
printf("Can't create thread: [%s]\n", strerror(error));
return 1;
}
But let's say I don't want to pass it by reference... Is there way to pass, say... an int, by value as an argument without the compiler warning me?