Professional Documents
Culture Documents
Semaphore
Semaphore
h>
#include<pthread.h>
#include<semaphore.h>
void* func1();
void *func2();
sem_t s;
int shared =1;
int main()
{
sem_init(&s,0,1);
pthread_t t1,t2;
pthread_create(&t1,NULL,func1,NULL);
pthread_join(t1,NULL);
pthread_create(&t2,NULL,func2,NULL);
pthread_join(t2,NULL);
void *func1()
{
int x;
sem_wait(&s);
x=shared;
x++;
sleep(1);
shared=x;
sem_post(&s);
}
void *func2()
{
int y;
sem_wait(&s);
y=shared;
y--;
sleep(1);
shared=y;
sem_post(&s);
}