-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.java
84 lines (77 loc) · 2.28 KB
/
Main.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
80
81
82
83
84
import java.util.*;
import java.util.concurrent.atomic.*;
class Main {
static CountingNetwork bitonic;
static AtomicInteger[] counts;
static int WIDTH = 16;
static int OPS = 1000;
// bitonic: bitonic counting network of WIDTH
// counts: atomic integers incremented by threads
// WIDTH: number of threads / width of network
// OPS: number of increments
// Each unbalanced thread tries to increment a
// random count. At the end, the counts would
// not be balanced.
//
// Each balanced thread tries to increment a
// random count, but this time, selected through
// a bitonic network. At the end, the counts
// should be balanced.
static Thread thread(int id, boolean balance) {
return new Thread(() -> {
for (int i=0; i<OPS; i++) {
int c = (int) (WIDTH * Math.random());
if (balance) c = bitonic.traverse(c);
counts[c].incrementAndGet();
Thread.yield();
}
log(id+": done");
});
}
// Initialize bitonic network and counts.
static void setup() {
bitonic = new BitonicNetwork(WIDTH);
counts = new AtomicInteger[WIDTH];
for (int i=0; i<WIDTH; i++)
counts[i] = new AtomicInteger(0);
}
// Test either unbalanced or balanced threads.
static void testThreads(boolean balance) {
setup();
Thread[] t = new Thread[WIDTH];
for (int i=0; i<WIDTH; i++) {
t[i] = thread(i, balance);
t[i].start();
}
try {
for (int i=0; i<WIDTH; i++)
t[i].join();
}
catch(InterruptedException e) {}
}
// Check if counts are balanced. At maximum
// counts should be separated by 1.
static boolean isBalanced() {
int v = counts[0].get();
for (int i=0; i<WIDTH; i++)
if (v-counts[i].get() > 1) return false;
return true;
}
// Test both unbalanced and balanced threads
// to check if counts stay balanced after they
// run their increments.
public static void main(String[] args) {
log("Starting unbalanced threads ...");
testThreads(false);
log(Arrays.deepToString(counts));
log("Counts balanced? "+isBalanced());
log("");
log("Starting balanced threads ...");
testThreads(true);
log(Arrays.deepToString(counts));
log("Counts balanced? "+isBalanced());
}
static void log(String x) {
System.out.println(x);
}
}