This repository was 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
/
Copy pathWaiter.cpp
112 lines (93 loc) · 2.11 KB
/
Waiter.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
//
// Created by barto on 16.04.18.
//
#include <iostream>
#include "Waiter.h"
using namespace std;
void Waiter::setState(unsigned char state) {
stateMutex.lock();
Waiter::state = state;
stateMutex.unlock();
}
Waiter::Waiter(int numberOfPhilosophers) {
terminate = false;
checkQueue = false;
this->numberOfPhilosophers = numberOfPhilosophers;
for (int i = 0; i < numberOfPhilosophers; i++) {
forks.push_back(true);
}
}
void Waiter::start() {
unique_lock<mutex> uniqueLock(waiterMutex);
setState(1);
while (!(terminate && queue.size() == 0)) {
waiterSleep.wait(uniqueLock, [this] {return checkQueue;});
forksQueueMutex.lock();
setState(2);
checkQueue = false;
int i = 0;
for (auto &philosopher : queue) {
int id = philosopher->getId();
int left = id;
int right = id + 1;
if (right == numberOfPhilosophers)
right = 0;
if (forks[left] && forks[right]) {
forks[left] = false;
forks[right] = false;
philosopher->wakeUp();
queue.erase(queue.begin() + i);
i--;
}
i++;
}
setState(1);
forksQueueMutex.unlock();
}
setState(3);
}
void Waiter::askForForks(Philosopher* p) {
forksQueueMutex.lock();
queue.push_back(p);
checkQueue = true;
waiterSleep.notify_all();
forksQueueMutex.unlock();
}
void Waiter::returnForks(Philosopher* p) {
int id = p->getId();
int left = id;
int right = id + 1;
if (right == numberOfPhilosophers)
right = 0;
forksQueueMutex.lock();
forks[left] = true;
forks[right] = true;
checkQueue = true;
waiterSleep.notify_all();
forksQueueMutex.unlock();
}
void Waiter::setTerminate(bool terminate) {
Waiter::terminate = terminate;
}
std::thread Waiter::spawnThread() {
return std::thread([this] { this->start(); });
}
void Waiter::wakeUp() {
forksQueueMutex.lock();
checkQueue = true;
waiterSleep.notify_all();
forksQueueMutex.unlock();
}
unsigned char Waiter::getState() {
stateMutex.lock();
unsigned char temp = state;
stateMutex.unlock();
return temp;
}
const vector<bool> Waiter::getForks() {
forksQueueMutex.lock();
vector<bool> temp;
temp = forks;
forksQueueMutex.unlock();
return temp;
}