-
Notifications
You must be signed in to change notification settings - Fork 0
/
1226_DiningPhilosophers.cpp
79 lines (67 loc) · 2.4 KB
/
1226_DiningPhilosophers.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
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
#include <condition_variable>
#include <functional>
#include <iostream>
#include <thread>
#include <vector>
class DiningPhilosophers {
private:
struct ForkWithID {
int id;
int ateCount;
bool leftFork;
};
std::vector<ForkWithID> mPhilosophers;
private:
std::mutex mMutex;
std::condition_variable mConditionVariable;
public:
DiningPhilosophers() {
for (size_t i = 0; i < 5; ++i) {
mPhilosophers.push_back(ForkWithID{0, 0, false});
}
}
void wantsToEat(int philosopher, std::function<void()> pickLeftFork,
std::function<void()> pickRightFork,
std::function<void()> eat, std::function<void()> putLeftFork,
std::function<void()> putRightFork) {
std::unique_lock<std::mutex> lock(mMutex);
mConditionVariable.wait(lock, [=]() {
int pos = (philosopher == 0 ? 4 : philosopher - 1);
return (mPhilosophers[philosopher].leftFork == false) &&
(mPhilosophers[pos].leftFork == false);
});
pickLeftFork();
mPhilosophers[philosopher].leftFork = true;
pickRightFork();
int pos = (philosopher == 0 ? 4 : philosopher - 1);
mPhilosophers[pos].leftFork = true;
eat();
mPhilosophers[philosopher].ateCount += 1;
putLeftFork();
mPhilosophers[philosopher].leftFork = false;
putRightFork();
mPhilosophers[pos].leftFork = false;
lock.unlock();
mConditionVariable.notify_all();
}
};
int main(int argc, char *argv[]) {
std::function<void()> pickLeftFork = []() { std::cout << "pickLeftFork\t"; };
std::function<void()> pickRightFork = []() {
std::cout << "pickRightFork\t";
};
std::function<void()> eat = []() { std::cout << "eat\t"; };
std::function<void()> putLeftFork = []() { std::cout << "putLeftFork\t"; };
std::function<void()> putRightFork = []() { std::cout << "putRightFork\t"; };
DiningPhilosophers diningPhilosophers;
std::vector<std::thread> threads;
for (size_t i = 0; i < 5; ++i) {
threads.push_back(std::thread(
&DiningPhilosophers::wantsToEat, &diningPhilosophers, i, pickLeftFork,
pickRightFork, eat, putLeftFork, putRightFork));
}
for (auto iter = threads.begin(); iter != threads.end(); ++iter) {
iter->join();
}
return 0;
}