cmultithreadingpthreadspthread-join

Confused about the argument in pthread_create()


My question :why not just pass &i as the last argument to pthread_create()? instead he create a array to hold the same thing....

#define THREAD_CT 2  /* bump this up a few numbers if you like */

void *print_stuff(void *ptr) {
  int i, id= * (int *) ptr;

  for (i= 0; i < 5; i++) {
    printf("Thread %d, loop %d.\n", id, i);
    sleep(rand() % 2);  /* sleep 0 or 1 seconds */
  }

  printf("Thread %d exiting.\n", id);

  return NULL;
}

int main(void) {
  pthread_t tids[THREAD_CT];
  int i, ids[THREAD_CT];

  for (i= 0; i < THREAD_CT; i++) {
    ids[i]= i;
    pthread_create(&tids[i], NULL, print_stuff, &ids[i]);
    printf("Main thread created thread %d (ID %ld).\n", i, tids[i]);
  }

  for (i= 0; i < THREAD_CT; i++) {
    pthread_join(tids[i], NULL);
    printf("Main thread reaped thread %d (ID %ld).\n", i, tids[i]);
  }

  return 0;
}


Solution

  • why not just pass &i as the last argument to pthread_create()?

    Because if you do that all threads will share the address i and there will be data race between threads.

    The alternative is to cast the value like:

    pthread_create(&tids[i], NULL, print_stuff, (void *)i);
    

    But this integer to pointer conversion has implementation-defined behaviour. So the way you have it now is probably the best way

    Also note that rand() is not thread-safe.