-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssignment5.cpp
More file actions
82 lines (69 loc) · 2.35 KB
/
Assignment5.cpp
File metadata and controls
82 lines (69 loc) · 2.35 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
Title: Producer-Consumer Problem
Class: SY-A
Roll No.: 41
Description: Simple simulation of the Producer-Consumer problem using semaphore-like variables.
*/
#include <iostream>
#include <cstdlib>
using namespace std;
int mutex = 1; // Used to ensure mutual exclusion (only one accesses buffer)
int full = 0; // Number of full slots in buffer
int emptySlots; // Number of empty slots (user will enter buffer size)
int item = 0; // Item number (used to track items produced/consumed)
// Wait function - simulates semaphore wait (decrement)
int wait(int s) {
return (--s);
}
// Signal function - simulates semaphore signal (increment)
int signal(int s) {
return (++s);
}
// Producer function
void producer() {
mutex = wait(mutex); // Lock critical section
full = signal(full); // Increase count of full slots
emptySlots = wait(emptySlots); // Decrease count of empty slots
item++; // Produce new item
cout << "\nProducer produced item " << item;
mutex = signal(mutex); // Unlock critical section
}
// Consumer function
void consumer() {
mutex = wait(mutex); // Lock critical section
full = wait(full); // Decrease full slots
emptySlots = signal(emptySlots); // Increase empty slots
cout << "\nConsumer consumed item " << item;
item--; // Consume an item
mutex = signal(mutex); // Unlock critical section
}
// Main function
int main() {
cout << "Enter buffer size: ";
cin >> emptySlots; // Initially all slots are empty
int choice;
cout << "\n1. Produce item\n2. Consume item\n3. Exit";
while (true) {
cout << "\n\nEnter your choice: ";
cin >> choice;
switch (choice) {
case 1: // Producer
if (mutex == 1 && emptySlots != 0)
producer();
else
cout << "\nBuffer is full! Cannot produce more items.";
break;
case 2: // Consumer
if (mutex == 1 && full != 0)
consumer();
else
cout << "\nBuffer is empty! Nothing to consume.";
break;
case 3: // Exit
exit(0);
default:
cout << "\nInvalid choice! Please try again.";
}
}
return 0;
}