-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSemaphore
56 lines (56 loc) · 993 Bytes
/
Semaphore
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<stdio.h>
#include<stdlib.h>
void producer();
void consumer();
int empty=2,full=0,item=0,mutex=1;
int wait(int s){
while(s<=0);
s--;
return s;
}
int signal(int s){
s++;
return s;
}
void producer(){
mutex=wait(mutex);
empty=wait(empty);
mutex=signal(mutex);
full=signal(full);
item++;
printf("Producer produces the item : %d\n",item);
//printf("Empty %d Full %d Mutex %d Item %d\n",empty,full,mutex,item);
}
void consumer(){
full=wait(full);
mutex=wait(mutex);
mutex=signal(mutex);
empty=signal(empty);
printf("Consumer consumes the item : %d\n",item--);
//printf("Empty %d Full %d Mutex %d Item %d\n",empty,full,mutex,item);
}
void main(){
int i,c;
printf("1 : Producer\n2 : Consumer\n3 : Exit\n");
do{
printf("Enter the choice : ");
scanf("%d",&c);
switch (c){
case 1:
if ((mutex==1)&&(empty!=0)){
producer();}
else{
printf("Buffer is full\n");}
break;
case 2:
if ((mutex==1)&&(full!=0)){
consumer();}
else{
printf("Buffer is empty\n");}
break;
case 3:
exit(0);
break;
}
}while(1);
}