Thread creation in C

Can somebody please explain why the following loop for thread creation fails without the sleep function call?

   for(t=0; t<NUM_THREADS; t++) {
      printf("Main: creating thread %d\n", t);
      rc = pthread_create(&thread[t], NULL, BusyWork, (void *)&t); 
      if (rc) {

If sleep is not inserted then thread function seems to take as an argument
an arbitrary integer between 0 ad NUM_THREADS.

I’m running this on an Ubuntu machine.

>Solution :

Because you are passing t as a pointer, then change t after creating the thread. So each thread refers to the same variable. Which also is a great candidate for race condition bugs. Simply don’t do that.

Instead create a hard copy per thread:

type* tmp = malloc(sizeof(t));
memcpy(tmp, &t, sizeof(t));
pthread_create(&thread[t], NULL, BusyWork, tmp);

void* BusyWork (void* arg)

Leave a Reply