Basically the main thread creates threads 1 2 3 4. And 1 2 3 have to wait for 4 to end and main waits for threads 1 2 3. The code is as follows:
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t id[4];
void *func1(void *arg)
{
printf("I am the %ith thread\n",(int)arg);
pthread_join(id[3],NULL);
printf("End of %ith thread\n",(int)arg);
pthread_exit(NULL);
}
void *func2(void *arg)
{
printf("I am the 4th thread\n");
sleep(5);
printf("End of 4th thread\n");
pthread_exit(NULL);
}
int main()
{
printf("Start of main thread\n");
pthread_create(&id[3],NULL,func2,NULL);
for(int i=0;i<3;i++)
{
pthread_create(&id[i],NULL,func1,(void *)i);
}
for(int i=0;i<3;i++)
{
pthread_join(id[i],NULL);
}
printf("End of main\n");
return 0;
}
When running I get something like this:
Start of main thread
I am the 0th thread
I am the 4th thread
I am the 2th thread
I am the 1th thread
End of 4th thread
End of 0th thread
In theory threads 1 2 3 should wait for 4 and then finish up themselves, but at every try only one thread finishes after 4 and then the entire execution is blocked indefinitely.
I tried making sure that the 4th thread always starts first with a pthread_attr_t and setting the sched-priority of the 4th high and that did not work unfortunately.
I tried looking up some details about pthread_join and if joining multiple threads to one threads is not safe or not allowed but I didn't find anything to suggest that.
From
pthread_join()manual page:If you need to wait for thread termination in multiple threads, create corresponding flag wrapped to condition variable. Broadcast condition variable either in terminating thread right before exit or after joining the thread in one of another threads.
Additional remarks:
pthread_exit(NULL)is redundant at the end of thread function. Just return NULL.inttovoid*and back may overflow, compiler don't like that. We could useintptr_tinstead ofintbut there is no conversion specifier forintptr_tinprintf(), so we should cast anyway. We can use intermediate casting tointptr_tto make compiler happy.The program may be like this:
UPD: There is simpler way: wrap
pthread_join()call into critical section guarded with mutex:In this case you don't need to join 4th thread in
main():