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.
CodePudding user response:
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);
}
CodePudding user response:
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.