While working with Threads in C, I'm facing the warning
"warning: cast to pointer from integer of different size"
The code is as follows
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<pthread.h>
void *print(void *id)
{
int a=10;
printf("My thread id is %ld\n",pthread_self());
printf("Thread %d is executing\n",id);
return (void *) 42;
}
int main()
{
pthread_t th[5];
int t;
int i;
int status;
void *ret;
for(i=0;i<5;i++)
{
status=pthread_create(&th[i],NULL,print,(void *)i); //Getting warning at this line
if(status)
{
printf("Error creating threads\n");
exit(0);
}
pthread_join(th[i],&ret);
printf("--->%d\n",(int *)ret);
}
pthread_exit(NULL);
}
Can anybody explain how to pass an integer to a function which receives (void * ) as a parameter?
you can pass the int value as void pointer like
(void *)&n
where n is integer, and in the function accept void pointer as parameter likevoid foo(void *n);
and finally inside the function convert void pointer to int like,int num = *(int *)n;
. this way you won't get any warning.change:
to:
The reinterpret_cast makes the int the size of a pointer and the warning will stop. Basically its a better version of (void *)i.
you can do something like this:
will output:
passing a unique pointer to each thread wont race, and you can get/save any kind of information in the th struct
This is a fine way to pass integers to new pthreads, if that is what you need. You just need to suppress the warning, and this will do it:
Discussion
This may offend your sensibilities, but it's very short and has no race conditions (as you'd have if you used
&i
). No sense in writing a few dozen lines of extra code just to get a bunch of numbered threads.Data races
Here is a bad version with a data race:
Now, what happens when I run it with the thread sanitizer?
(Also, check out how it prints "5" twice...)