1 import EDU.oswego.cs.dl.util.concurrent.*; 2 3 4 12 13 public class FibVCB extends FJTask { 14 15 static int sequentialThreshold = 1; 17 18 public static void main(String [] args) { 19 try { 20 int procs; 21 int num; 22 try { 23 procs = Integer.parseInt(args[0]); 24 num = Integer.parseInt(args[1]); 25 if (args.length > 2) sequentialThreshold = Integer.parseInt(args[2]); 26 } 27 catch (Exception e) { 28 System.out.println("Usage: java FibVCB <threads> <number> [<sequntialThreshold>]"); 29 return; 30 } 31 32 FJTaskRunnerGroup g = new FJTaskRunnerGroup(procs); 33 FibVCB f = new FibVCB(num, null); 34 g.invoke(f); 35 g.stats(); 36 37 long result = f.getAnswer(); 38 System.out.println("FibVCB: Size: " + num + " Answer: " + result); 39 } 40 catch (InterruptedException ex) {} 41 } 42 43 44 volatile int number = 0; 45 final FibVCB parent; int callbacksExpected = 0; 47 volatile int callbacksReceived = 0; 48 49 FibVCB(int n, FibVCB p) { number = n; parent = p; } 50 51 synchronized void addResult(int n) { 53 number += n; 54 ++callbacksReceived; 55 } 56 57 synchronized int getAnswer() { 58 if (!isDone()) throw new Error ("Not yet computed"); 59 return number; 60 } 61 62 public void run() { int n = number; 64 65 if (n <= 1) { 66 } 68 69 else if (n <= sequentialThreshold) { 70 number = seqFib(n); 71 } 72 73 else { 74 number = 0; 76 77 callbacksExpected = 2; 79 80 81 new FibVCB(n - 1, this).fork(); 82 new FibVCB(n - 2, this).fork(); 83 84 while (callbacksReceived < callbacksExpected) yield(); 86 } 87 88 if (parent != null) parent.addResult(number); 90 } 91 92 93 static int seqFib(int n) { 95 if (n <= 1) 96 return n; 97 else 98 return seqFib(n-1) + seqFib(n-2); 99 } 100 101 } 102 103 | Popular Tags |