1 |
import java.util.concurrent.*; |
2 |
|
3 |
public final class DynamicFib extends RecursiveAction { |
4 |
static int procs; |
5 |
static long lastStealCount; // to display steal counts |
6 |
|
7 |
/** for time conversion */ |
8 |
static final long NPS = (1000L * 1000 * 1000); |
9 |
|
10 |
public static void main(String[] args) throws Exception { |
11 |
procs = 0; |
12 |
int num = 45; |
13 |
try { |
14 |
if (args.length > 0) |
15 |
procs = Integer.parseInt(args[0]); |
16 |
if (args.length > 1) |
17 |
num = Integer.parseInt(args[1]); |
18 |
} |
19 |
catch (Exception e) { |
20 |
System.out.println("Usage: java DynamicFib <threads> <number>"); |
21 |
return; |
22 |
} |
23 |
for (int reps = 0; reps < 2; ++reps) { |
24 |
ForkJoinPool pool = procs == 0? new ForkJoinPool() : |
25 |
new ForkJoinPool(procs); |
26 |
for (int i = 0; i < 20; ++i) |
27 |
test(pool, num); |
28 |
System.out.println(pool); |
29 |
pool.shutdown(); |
30 |
} |
31 |
} |
32 |
|
33 |
static void test(ForkJoinPool pool, int num) throws Exception { |
34 |
int ps = pool.getParallelism(); |
35 |
long start = System.nanoTime(); |
36 |
DynamicFib f = new DynamicFib(num); |
37 |
pool.invoke(f); |
38 |
long time = System.nanoTime() - start; |
39 |
double secs = ((double)time) / NPS; |
40 |
long result = f.number; |
41 |
System.out.print("DynamicFib " + num + " = " + result); |
42 |
System.out.printf("\tTime: %9.3f", secs); |
43 |
long sc = pool.getStealCount(); |
44 |
long ns = sc - lastStealCount; |
45 |
lastStealCount = sc; |
46 |
System.out.printf(" Steals: %4d", ns/ps); |
47 |
System.out.printf(" Workers: %4d", pool.getPoolSize()); |
48 |
System.out.println(); |
49 |
} |
50 |
|
51 |
|
52 |
int number; // Initialized with argument; replaced with result |
53 |
DynamicFib(int n) { number = n; } |
54 |
public void compute() { |
55 |
number = fib(number); |
56 |
} |
57 |
|
58 |
static int fib(int n) { |
59 |
int res; |
60 |
if (n <= 1) |
61 |
res = n; |
62 |
else if (getSurplusQueuedTaskCount() >= 4) |
63 |
res = seqFib(n); |
64 |
else { |
65 |
DynamicFib f2 = new DynamicFib(n - 2); |
66 |
f2.fork(); |
67 |
res = fib(n - 1); |
68 |
if (f2.tryUnfork()) |
69 |
res += fib(n - 2); |
70 |
else { |
71 |
f2.quietlyJoin(); |
72 |
res += f2.number; |
73 |
} |
74 |
} |
75 |
return res; |
76 |
} |
77 |
|
78 |
// Sequential version for arguments less than threshold |
79 |
static final int seqFib(int n) { // unroll left only |
80 |
int r = 1; |
81 |
do { |
82 |
int m = n - 2; |
83 |
r += m <= 1 ? m : seqFib(m); |
84 |
} while (--n > 1); |
85 |
return r; |
86 |
} |
87 |
|
88 |
} |
89 |
|