1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* http://creativecommons.org/licenses/publicdomain |
5 |
*/ |
6 |
|
7 |
//import jsr166y.*; |
8 |
import java.util.*; |
9 |
import java.util.concurrent.*; |
10 |
|
11 |
public final class DynamicLeftSpineFib extends RecursiveAction { |
12 |
|
13 |
// Performance-tuning constant: |
14 |
static long lastStealCount; |
15 |
|
16 |
public static void main(String[] args) throws Exception { |
17 |
int procs = 0; |
18 |
int num = 43; |
19 |
try { |
20 |
if (args.length > 0) |
21 |
procs = Integer.parseInt(args[0]); |
22 |
if (args.length > 1) |
23 |
num = Integer.parseInt(args[1]); |
24 |
} |
25 |
catch (Exception e) { |
26 |
System.out.println("Usage: java DynamicLeftSpineFib <threads> <number> [<sequentialThreshold>]"); |
27 |
return; |
28 |
} |
29 |
|
30 |
|
31 |
for (int reps = 0; reps < 2; ++reps) { |
32 |
ForkJoinPool g = procs == 0? new ForkJoinPool() : |
33 |
new ForkJoinPool(procs); |
34 |
lastStealCount = g.getStealCount(); |
35 |
for (int i = 0; i < 10; ++i) { |
36 |
test(g, num); |
37 |
} |
38 |
System.out.println(g); |
39 |
g.shutdown(); |
40 |
} |
41 |
} |
42 |
|
43 |
static void test(ForkJoinPool g, int num) throws Exception { |
44 |
int ps = g.getParallelism(); |
45 |
long start = System.currentTimeMillis(); |
46 |
DynamicLeftSpineFib f = new DynamicLeftSpineFib(num, null); |
47 |
g.invoke(f); |
48 |
long time = System.currentTimeMillis() - start; |
49 |
double secs = ((double)time) / 1000.0; |
50 |
long result = f.getAnswer(); |
51 |
System.out.print("DynamicLeftSpineFib " + num + " = " + result); |
52 |
System.out.printf("\tTime: %7.3f", secs); |
53 |
long sc = g.getStealCount(); |
54 |
long ns = sc - lastStealCount; |
55 |
lastStealCount = sc; |
56 |
System.out.printf(" Steals/t: %5d", ns/ps); |
57 |
System.out.printf(" Workers: %8d", g.getPoolSize()); |
58 |
System.out.println(); |
59 |
} |
60 |
|
61 |
|
62 |
// Initialized with argument; replaced with result |
63 |
int number; |
64 |
DynamicLeftSpineFib next; |
65 |
|
66 |
DynamicLeftSpineFib(int n, DynamicLeftSpineFib nxt) { |
67 |
number = n; next = nxt; |
68 |
} |
69 |
|
70 |
int getAnswer() { |
71 |
return number; |
72 |
} |
73 |
|
74 |
public final void compute() { |
75 |
int n = number; |
76 |
if (n > 1) { |
77 |
DynamicLeftSpineFib rt = null; |
78 |
while (n > 1 && getSurplusQueuedTaskCount() <= 3) { |
79 |
(rt = new DynamicLeftSpineFib(n - 2, rt)).fork(); |
80 |
n -= 1; |
81 |
} |
82 |
int r = seqFib(n); |
83 |
while (rt != null) { |
84 |
if (rt.tryUnfork()) rt.compute(); else rt.helpJoin(); |
85 |
r += rt.number; |
86 |
rt = rt.next; |
87 |
} |
88 |
number = r; |
89 |
} |
90 |
} |
91 |
|
92 |
// Sequential version for arguments less than threshold |
93 |
static int seqFib(int n) { |
94 |
if (n <= 1) |
95 |
return n; |
96 |
else |
97 |
return seqFib(n-1) + seqFib(n-2); |
98 |
} |
99 |
|
100 |
} |