-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththeDiningPhilosophers.cpp
40 lines (35 loc) · 1014 Bytes
/
theDiningPhilosophers.cpp
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
// Source: https://leetcode.com/problems/the-dining-philosophers/
// Author: Miao Zhang
// Date: 2021-04-18
class DiningPhilosophers {
public:
DiningPhilosophers() {
}
void wantsToEat(int philosopher,
function<void()> pickLeftFork,
function<void()> pickRightFork,
function<void()> eat,
function<void()> putLeftFork,
function<void()> putRightFork) {
int l = philosopher;
int r = (philosopher + 4) % 5;
if (philosopher % 2 == 0) { // left -> right
lock[l].lock();
pickLeftFork();
lock[r].lock();
pickRightFork();
} else {
lock[r].lock();
pickRightFork();
lock[l].lock();
pickLeftFork();
}
eat();
putLeftFork();
lock[l].unlock();
putRightFork();
lock[r].unlock();
}
private:
std::mutex lock[5];
};