0

I would like to ask that PrintHello accepts a void pointer but how come you can equate it to an integer directly ???
" tid = (int)threadid; "
while at the same time instead if a pointer a normal variable was passed into this function
" pthread_create(&threads[t], NULL, PrintHello, (void *)t); "

the above construct is taken from
https://computing.llnl.gov/tutorials/pthreads/#PassingArguments

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS     5

void *PrintHello(void *threadid)
{
   int tid;
   tid = (int)threadid;
   printf("Hello World! It's me, thread #%d!\n", tid);
   pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc, t;
   for(t=0; t<NUM_THREADS; t++){
      printf("In main: creating thread %d\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);
}
2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by Belrog
0

To put it simply: By casting the variable you are telling the compiler you know what you are doing, and not to check the variable type. The actual value of the variable stays the same, but you just tell the compiler to use them differently.

Most variables boils down to just a bit of data at a memory position. If you want to pretend a int is a char, nobody is going to stop you :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.