-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathT18_10_Thread_Philosophers_NonBlock.cpp
78 lines (57 loc) · 1.68 KB
/
T18_10_Thread_Philosophers_NonBlock.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
/*
Implement a solution to the dining philosophers problem.The solution should be non - blocking and dead - lock free.
*/
#include "stdafx.h"
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <vector>
#include <memory>
using namespace std;
class Fork
{
public:
Fork(){};
Fork(int ind) : ind{ ind }{};
mutex m;
int ind;
};
void Act(Fork* leftFork, Fork* rightFork, int philosopherNumber)
{
int res = 0;
do{
res = try_lock(leftFork->m, rightFork->m);
if (res == -1) {
lock_guard<mutex> a(leftFork->m, adopt_lock);
lock_guard<mutex> b(rightFork->m, adopt_lock);
string s = "Philosopher " + to_string(philosopherNumber) + " picked " + to_string(leftFork->ind) + " fork and " + to_string(rightFork->ind) + " fork.\n";
cout << s;
s = "Philosopher " + to_string(philosopherNumber) + " eats\n";
this_thread::sleep_for(chrono::milliseconds(50));
cout << s;
}
else{
string s = "Philosopher " + to_string(philosopherNumber) + " thinks\n";
cout << s;
this_thread::sleep_for(chrono::milliseconds(50));
}
} while (res != -1);
};
int main()
{
static const int PHIL_MAX = 5;
vector< unique_ptr<Fork> > fork(PHIL_MAX);
for (int i = 0; i < PHIL_MAX; ++i){
auto f = unique_ptr<Fork>(new Fork(i));
fork[i] = move(f);
}
vector<thread> phil(PHIL_MAX);
for (int i = 0; i < PHIL_MAX; ++i){
phil[i] = (thread(Act, fork[i == 0 ? PHIL_MAX - 1 : i - 1].get(), fork[i].get(), i));
}
for (auto& t : phil){
t.join();
}
return 0;
}