Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legitimate to pass an argument as void*?

Tags:

c

void

pthreads

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);
}
like image 997
Aditya Sehgal Avatar asked Jun 04 '10 09:06

Aditya Sehgal


2 Answers

This works as long as sizeof(long) <= sizeof(void*), and that every value of long can be represented as a void*.

Better would be to pass the address of the variable. You can cast from a T* to void*, and back again safely and without assumption.

like image 113
GManNickG Avatar answered Sep 28 '22 19:09

GManNickG


It's as legitimate as any kind of typecasting. The point is that nothing can be done with the value the argument points to, until it is typecast, hence tid = (long)threadid.

Check the older Q&A When to use a void pointer?.

like image 26
Charles Stewart Avatar answered Sep 28 '22 20:09

Charles Stewart