I have just started learning pthreads API and I am following the tutorial here
However, in an example program of pthread_create
, the sample program creates a long variable and passes its value, typecasted as void*
. In the thread entry function, it dereferences it just like a long.
Is this legit?
I understand if I pass the address of variable t
, every thread would be acting on the same variable and not on a copy of it. Can we do this because it's a void*
and the compiler has no idea about what type we are sending?
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}