Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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); 
      sleep(1);
      if (rc) {
         perror("pthread_create");
         exit(EXIT_FAILURE);
         }
      }

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
{
  ...
  free(arg);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading