We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 30f14e4 commit 87d6012Copy full SHA for 87d6012
C++/the-dining-philosophers.cpp
@@ -0,0 +1,35 @@
1
+// Time: O(n)
2
+// Space: O(1)
3
+
4
+class DiningPhilosophers {
5
+public:
6
+ DiningPhilosophers()
7
+ : m_(5) {
8
9
+ }
10
11
+ void wantsToEat(int philosopher,
12
+ function<void()> pickLeftFork,
13
+ function<void()> pickRightFork,
14
+ function<void()> eat,
15
+ function<void()> putLeftFork,
16
+ function<void()> putRightFork) {
17
18
+ int left = philosopher, right = (philosopher + 4) % 5;
19
+ int first = left, second = right;
20
+ if (philosopher % 2) {
21
+ swap(first, second);
22
23
24
+ unique_lock<mutex> lock1(m_[first]);
25
+ unique_lock<mutex> lock2(m_[second]);
26
+ pickLeftFork();
27
+ pickRightFork();
28
+ eat();
29
+ putLeftFork();
30
+ putRightFork();
31
32
33
+private:
34
+ vector<mutex> m_;
35
+};
0 commit comments