-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproducerconsumer.c
65 lines (58 loc) · 1.18 KB
/
producerconsumer.c
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
57
58
59
60
61
62
63
64
65
// write a code to stimulate producer consumer problem with semaphore
#include <stdio.h>
#include <stdlib.h>
int muter = 1, full = 0, empty = 3, x = 0;
int wait(int s)
{
return (--s);
}
int signal(int s)
{
return (++s);
}
void producer()
{
muter = wait(muter);
full = signal(full);
empty = wait(empty);
x++;
printf("\nProducer produces the item %d", x);
muter = signal(muter);
}
void consumer()
{
muter = wait(muter);
full = wait(full);
empty = signal(empty);
printf("\nConsumer consumes item %d", x);
x--;
muter = signal(muter);
}
int main()
{
int n;
printf("Enter 1 for Producer, 2 for Consumer, 3 to Exit\n");
while (1)
{
printf("\nEnter your choice: ");
scanf("%d", &n);
switch (n)
{
case 1:
if (muter == 1 && empty != 0)
producer();
else
printf("Buffer is full!\n");
break;
case 2:
if (muter == 1 && full != 0)
consumer();
else
printf("Buffer is empty!\n");
break;
case 3:
exit(0);
break;
}
}
}