sem_wait, sem_post confusion?

Hi friends,
I have written this small program using the concept of semaphores. I am a bit confused, hope u can help me with it.
The idea is that

  1. Two threads are created
  2. First will be displaying 0(zero) on the screen
  3. Second will be displaing 1(one) on the screen
  4. This process will go on upto three times for each thread, it would look like
 
0
 
1
 
0
 
1
 
0
 
1
 

But the program that i have written prints like this
0

0

0

1

1

1

I don't really know what I am missing here, could you pin point it to me, I think my concept of semaphores is corrct.
You can have a look at my code

 
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <sys/sem.h>
#include <semaphore.h>
sem_t mysem;
void *thread(void *);
int main()
{
        sem_init(&mysem,0,1);
        pthread_t tid[2];
 
        pthread_attr_t attr[2];
        pthread_attr_init(&attr[0]);
        pthread_attr_init(&attr[1]);
        {
        pthread_create(&tid[0],&attr[0],thread,(void *)0);
        pthread_create(&tid[1],&attr[1],thread,(void *)1);
        }
        {
        pthread_join(tid[0],NULL);
        pthread_join(tid[1],NULL);
        }
        printf("\nThreads finished!\n");
        return 0;
}
void *thread(void *n)
{
        int i;
        i = (int)n;
        int x = 0;
        while(x < 3)
        {
        sem_wait(&mysem);
        printf("%d\n\n",i);
        sem_post(&mysem);
        x++;
        }
        pthread_exit(0);
}

But the same program works when I put a sleep(1) in the middle like this

void *thread(void *n)
{
        int i;
        i = (int)n;
        int x = 0;
        while(x < 3)
        {
        sem_wait(&mysem);
        printf("%d\n\n",i);
        sem_post(&mysem);
        x++;
        sleep(1);
        }
        pthread_exit(0);
}

But I want to achieve what I want to achieve by using only semaphores, no sleep function,

Thanks
Looking forward to your lovely replies.

define another two semaphore:

sem_t zero, one;

a thread wait for zero and post one, while the other thread wait for one and post zero.

1 Like

Thanks a ton buddy!