-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtournament.cpp
67 lines (59 loc) · 2.3 KB
/
tournament.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
#include <iostream>
#include <cmath>
#include <thread>
#include "tournament.h"
bool tournament :: instance = false;
tournament* tournament :: m = NULL;
tournament :: tournament(int i) {
// extend the number of processes to the next exponent of 2
int q = (int) pow(2, (int) ceil(log2(i)));
// number of nodes in complete tree = number of leaves + (number of leaves - 1)
n = q + (q - 1);
// points to first leaf (process)
p = q - 1;
z = i;
// initialize a 2d array.[process * level/process]
process = new int[i * z];
flag = new bool[n];
victim = new int[q - 1];
for(int j = 0; j < i * z; ++j)
process[j] = -1;
for(int j = 0; j < n; ++j)
flag[j] = false;
}
tournament :: ~tournament() {
delete[] process;
delete[] flag;
delete[] victim;
}
tournament* tournament :: getLock(int n) {
if(!instance) {
m = new tournament(n);
instance = true;
}
return m;
}
void tournament :: lock(int pid) {
int ipid = p + pid - 1; // pid is indexed from 1.
// ipid is index of flag[]
int k = (int) ceil(log2(z)); // number oof levels = height(tree)
for(int i = 0; i < k; ++i) {
flag[ipid] = true;
victim[(ipid - 1) / 2] = pid;
if(ipid % 2 == 0) {
while(flag[ipid - 1] & (victim[(ipid - 1) / 2] == pid)) // if other process is not requesing CS
std :: this_thread :: yield();
} else { // move ahead by just checking the flag
while(flag[ipid + 1] & (victim[(ipid - 1) / 2] == pid)) // otherwise, check victim
std :: this_thread :: yield();
}
process[(pid - 1) * z + i] = ipid; // store the index for unlocking
ipid = (ipid - 1) / 2;
}
}
void tournament :: unlock(int pid) {
int k = (int) ceil(log2(z)); // number of levels = height(tree)
for(int j = 0; j < k; ++j) {
flag[process[(pid - 1) * z + j]] = false; // unlock using stored index
}
}