#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
static sem_t sem1,sem2,sem3;
int global = 0;
#define MAX 15
void *t1_exe(void *arg){
while (global<MAX) {
sem_wait(&sem1) ;
printf("In thread1 %lu\n",pthread_self());
global++;
sem_post(&sem2);
sleep(1);
}
}
void *t2_exe(void *arg){
while (global<MAX) {
sem_wait(&sem2) ;
printf("In thread2 %lu\n",pthread_self());
global++;
sem_post(&sem3);
sleep(1);
}
}
void *t3_exe(void *arg){
while (global<MAX) {
sem_wait(&sem3) ;
printf("In thread3 %lu\n",pthread_self());
global++;
sem_post(&sem1);
sleep(1);
}
}
void main()
{
int i;
pthread_t t_a[3];
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
sem_init(&sem3,0,0);
pthread_create(&t_a[0],NULL,t1_exe,(void *)NULL);
pthread_create(&t_a[1],NULL,t2_exe,(void *)NULL);
pthread_create(&t_a[2],NULL,t3_exe,(void *)NULL);
for(i=0;i<3;i++)
pthread_join(t_a[i],NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
sem_destroy(&sem3);
return ;
}