I have the following code:
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
sem_t semr;
void* func(void* i)
{
sem_wait(&semr);
printf("\nInstance %d running",*(int*)i);
//sem_post(&semr);
return NULL;
}
int main(void)
{
sem_init(&semr,0,1);
void* (*fp)(void*);
int s1,s2,s3,val=0;
pthread_t t1,t2,t3;
fp=&func;
val=1;
s1=pthread_create(&t1,NULL,fp,(void*)&val);
val=2;
s2=pthread_create(&t2,NULL,fp,(void*)&val);
val=3;
s3=pthread_create(&t3,NULL,fp,(void*)&val);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_join(t3,NULL);
return 0;
}
This is my understanding of what happens:
The first thread(t1) executes successfully. The subsequent threads(t2 and t3) though, are blocked, since I never sem_post the semaphore. The pthread_joins will make main() wait for all 3 threads to terminate.
This is what happens:
Neither thread will output anything. Not even t1s output(see question 1 below)
However,
removing all pthread_joins has a better effect in terms of what I expect:
t1 executes successfully and the command prompt is returned.
My questions:
-
According to the sample code on this page,
main()should wait fort2andt3to terminate (in addition to successfully executingt1and outputting something). Am I usingpthread_joinincorrectly here? What’s happening? -
Why happens to the blocked threads(
t2andt3)? Are the threads forced to terminate due tomain()returning?
You should ensure that anything you print is terminated (not followed) with a newline.
stdoutwon’t be flushed whilemainis blocked waiting to join your threads. When you explicitly cancel the program, again,stdoutwon’t be flushed.