-
Notifications
You must be signed in to change notification settings - Fork 0
/
Process.java
80 lines (55 loc) · 1.75 KB
/
Process.java
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
import java.util.concurrent.atomic.AtomicIntegerArray;
public class Process implements Runnable{
// shared static variables
volatile static AtomicIntegerArray[] flag;
volatile static AtomicIntegerArray[] turn;
static int levels = -1;
// shared counter
static int counter = 0;
private int ID;
private int node;
private String binaryID;
static int NUMBER_OF_ITERATIONS = 1000;
public Process(int id, int n){
this.ID = id;
this.binaryID = Integer.toBinaryString(id);
}
@Override
public void run(){
try {
doWork();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void doWork() throws InterruptedException {
for (int i=0; i < NUMBER_OF_ITERATIONS; i++) {
lock();
counter++;
unlock();
}
}
public void lock() throws InterruptedException {
node = ID;
for (int i=0; i < levels; i++) {
int idThisLevel = 0;
if (i < binaryID.length()){
idThisLevel = binaryID.charAt(binaryID.length()-1-i) - '0';
}
node = node/2;
flag[i].set(2 * node + idThisLevel, 1);
turn[i].set(node, 1 - idThisLevel);
while ( flag[i].get(2 * node + 1 - idThisLevel) == 1 && (turn[i].get(node) != idThisLevel)) {};
}
}
public void unlock(){
for (int i=levels-1; i >= 0; i--){
int idThisLevel = 0;
if (i < binaryID.length()){
idThisLevel = binaryID.charAt(binaryID.length()-1-i) - '0';
}
flag[i].set(2 * node + idThisLevel, 0);
node = (int) (ID / Math.pow(2, i));
}
}
}