Skip to content

Commit 87d6012

Browse files
authored
Create the-dining-philosophers.cpp
1 parent 30f14e4 commit 87d6012

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

C++/the-dining-philosophers.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)