Your browser does not support JavaScript and this site utilizes JavaScript to build content and provide links to additional information. You should either enable JavaScript in your browser settings or use a browser that supports JavaScript in order to take full advantage of this site.
1 import EDU.oswego.cs.dl.util.concurrent.*; 2 import java.net.*; 3 import java.io.*; 4 5 13 14 public class SFib extends FJTask { 15 16 static int sequentialThreshold = 0; 18 19 public static void main(String [] args) { 20 try { 21 int procs; 22 try { 24 procs = Integer.parseInt(args[0]); 25 if (args.length > 2) sequentialThreshold = Integer.parseInt(args[2]); 27 } 28 catch (Exception e) { 29 System.out.println("Usage: java SFib <threads> <number> [<sequntialThreshold>]"); 30 return; 31 } 32 33 FJTaskRunnerGroup group = new FJTaskRunnerGroup(procs); 34 ServerSocket socket = new ServerSocket(1618); 35 for (;;) { 36 final Socket connection = socket.accept(); 37 group.execute(new Handler(connection)); 38 } 39 40 } 41 catch (Exception e) { e.printStackTrace(); } 42 } 43 44 static class Handler extends FJTask { 45 final Socket s; 46 Handler(Socket s) { this.s = s; } 47 public void run() { 48 try { 49 DataInputStream i = new DataInputStream(s.getInputStream()); 50 DataOutputStream o = new DataOutputStream(s.getOutputStream()); 51 int n = i.readInt(); 52 SFib f = new SFib(n); 53 invoke(f); 54 o.writeInt(f.getAnswer()); 55 } 56 catch (Exception e) { e.printStackTrace(); } 57 } 58 } 59 60 61 volatile int number; 63 64 SFib(int n) { number = n; } 65 66 int getAnswer() { 67 if (!isDone()) throw new Error ("Not yet computed"); 68 return number; 69 } 70 71 72 public void run() { 73 int n = number; 74 75 if (n <= 1) { 77 } 79 else if (n <= sequentialThreshold) { 81 number = seqFib(n); 82 } 83 else { 85 SFib f1 = new SFib(n - 1); 87 SFib f2 = new SFib(n - 2); 88 89 coInvoke(f1, f2); 91 92 number = f1.number + f2.number; 94 } 96 } 97 98 static int seqFib(int n) { 100 if (n <= 1) 101 return n; 102 else 103 return seqFib(n-1) + seqFib(n-2); 104 } 105 106 } 107 108
| Popular Tags
|