-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbakery.cpp
62 lines (53 loc) · 1.65 KB
/
bakery.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
#include <iostream>
#include <thread>
#include "bakery.h"
bool bakery :: instance = false;
bakery* bakery :: m = NULL;
bakery :: bakery(int i) {
n = i;
choosing = new bool[n];
token = new int[n];
for(int i = 0; i < n + 1; i++)
choosing[i] = false;
for(int i = 0; i < n; i++)
token[i] = 0;
}
bakery :: ~bakery() {
delete[] choosing;
delete[] token;
instance = false;
}
bakery* bakery :: getLock(int n) {
if(!instance) {
m = new bakery(n);
instance = true;
}
return m;
}
void bakery :: lock(int pid) {
pid -= 1;
choosing[pid] = true; // DOORWAY section
token[pid] = 1 + bakery :: max(token); // set token one greater than max present
choosing[pid] = false;
for(int j = 0; j < n; ++j) { // WAITING section
if(j != pid) {
while(choosing[j] == true) // wait till everyone has a token
std :: this_thread :: yield();
while((token[j] != 0) && // compare everyone's pair with seld
// thread with lowest pair gets the lock
(token[pid] > token[j] || (token[pid] == token[j] && pid > j)))
std :: this_thread :: yield();
}
}
}
void bakery :: unlock(int pid) {
pid -= 1;
token[pid] = 0; // set the token to minimum
}
int bakery :: max(volatile int token[]) {
int m = token[0];
for(int i = 1; i < n; ++i) {
m = token[i] > m? token[i] : m;
}
return m;
}