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.