-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem-29
More file actions
67 lines (59 loc) · 1.47 KB
/
problem-29
File metadata and controls
67 lines (59 loc) · 1.47 KB
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
66
67
#include <stdio.h>
#include <stdlib.h>
int mutex = 1; // Semaphore for critical section
int full = 0; // Count of full slots
int empty = 10; // Count of empty slots
int x = 0; // Item count
void producer() {
// Entry section (critical section start)
--mutex;
++full;
--empty;
x++;
printf("\nProducer produces item %d", x);
++mutex;
// Exit section (critical section end)
}
void consumer() {
// Entry section (critical section start)
--mutex;
--full;
++empty;
printf("\nConsumer consumes item %d", x);
x--;
++mutex;
// Exit section (critical section end)
}
int main() {
int n, i;
printf("\n1. Press 1 for Producer"
"\n2. Press 2 for Consumer"
"\n3. Press 3 for Exit");
for (i = 1; i > 0; i++) {
printf("\nEnter your choice: ");
scanf("%d", &n);
switch (n) {
case 1:
if (mutex == 1 && empty != 0) {
producer();
} else {
printf("Buffer is full!");
}
break;
case 2:
if (mutex == 1 && full != 0) {
consumer();
} else {
printf("Buffer is empty!");
}
break;
case 3:
exit(0);
break;
default:
printf("Invalid choice!");
break;
}
}
return 0;
}