This repository has been archived by the owner on May 27, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Philosopher.cpp
87 lines (70 loc) · 1.68 KB
/
Philosopher.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
80
81
82
83
84
85
86
87
//
// Created by baatochan on 3/14/18.
//
#include <random>
#include <chrono>
#include <mutex>
#include "Philosopher.h"
#include "Waiter.h"
using namespace std;
void Philosopher::setState(unsigned char state) {
stateMutex.lock();
Philosopher::state = state;
stateMutex.unlock();
}
void Philosopher::think(unsigned int deciseconds) {
setState(1);
this_thread::sleep_for(chrono::milliseconds(deciseconds*100));
}
void Philosopher::eat() {
forksAvalibityMutex.lock();
setState(2);
waiter->askForForks(this);
forksAvalibityMutex.unlock();
philosopherSleep.wait(uniqueLock, [this]{return forksAvailable;});
forksAvalibityMutex.lock();
setState(3);
this_thread::sleep_for(chrono::seconds(2));
forksAvailable = false;
waiter->returnForks(this);
forksAvalibityMutex.unlock();
}
void Philosopher::live() {
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<int> dist(1, 100);
uniqueLock = unique_lock<mutex>(philosopherMutex);
while (!terminate) {
think((unsigned int) dist(mt));
eat();
}
setState(4);
}
Philosopher::Philosopher(unsigned int id, Waiter* waiter) {
this->id = id;
this->waiter = waiter;
forksAvailable = false;
terminate = false;
setState(0);
}
std::thread Philosopher::spawnThread() {
return std::thread([this] { this->live(); });
}
unsigned char Philosopher::getState() {
stateMutex.lock();
unsigned char temp = state;
stateMutex.unlock();
return temp;
}
unsigned int Philosopher::getId() {
return id;
}
void Philosopher::wakeUp() {
forksAvalibityMutex.lock();
forksAvailable = true;
philosopherSleep.notify_all();
forksAvalibityMutex.unlock();
}
void Philosopher::setTerminate(bool terminate) {
Philosopher::terminate = terminate;
}