Kedar Paranjape
Kedar Paranjape

Reputation: 1842

POSIX semaphores/threads not working correctly?

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:

  1. According to the sample code on this page, main() should wait for t2 and t3 to terminate (in addition to successfully executing t1 and outputting something). Am I using pthread_join incorrectly here? What's happening?

  2. Why happens to the blocked threads(t2 and t3)? Are the threads forced to terminate due to main() returning?

Upvotes: 0

Views: 1522

Answers (1)

CB Bailey
CB Bailey

Reputation: 791421

You should ensure that anything you print is terminated (not followed) with a newline. stdout won't be flushed while main is blocked waiting to join your threads. When you explicitly cancel the program, again, stdout won't be flushed.

Upvotes: 3

Related Questions