-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdining_philosophers.cpp
More file actions
72 lines (63 loc) · 1.6 KB
/
dining_philosophers.cpp
File metadata and controls
72 lines (63 loc) · 1.6 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
#include <bits/stdc++.h>
using namespace std;
class diningMonitor
{
public:
int state[5] = {0};
//0-thinking, 1-hungry 2-eating
void test(int i)
{
if ((state[(i + 4) % 5] != 2) && state[i] == 1 && state[(i + 1) % 5] != 2)
{
cout << "Philosopher " << i << " is eating.\n";
state[i] = 2;
}
}
void pickup(int i)
{
state[i] = 1;
test(i);
if (state[i] != 2)
{
cout << "Philosopher " << i << " remains hungry.\n";
}
}
void putdown(int i)
{
cout << "Philosopher " << i << " completed eating and is now in thinking state.\n";
state[i] = 0;
test((i + 4) % 5);
test((i + 1) % 5);
}
};
int main()
{
diningMonitor dm;
char n = 'y';
while (n != 'n')
{
cout << "\n thinking Philosophers :";
for (int i = 0; i < 5; i++)
if (dm.state[i] == 0)
cout << "\t" << i;
cout << "\n hungry Philosophers:";
for (int i = 0; i < 5; i++)
if (dm.state[i] == 1)
cout << "\t" << i;
cout << "\n eating philosophers:";
for (int i = 0; i < 5; i++)
if (dm.state[i] == 2)
cout << "\t" << i;
cout << "\n";
cout << "\n Enter the philosopher number (0-4) and its action \n 0 for stop eating, 1 for hungry : \n";
int a, b;
cin >> a >> b;
if (b)
dm.pickup(a);
else
dm.putdown(a);
cout << "\npress y to continue, else press n";
cin >> n;
}
return 0;
}