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 %dn", 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.
2
Answers
You’re passing the same pointer to each thread, but still expecting each to see different values, which is not how things work.
I don’t think it’s a good idea to let the main program end without doing anything to collect/join the threads back together, either.
Because you are passing
t
as a pointer, then changet
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: