OLD | NEW |
1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file | 1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file |
2 // for details. All rights reserved. Use of this source code is governed by a | 2 // for details. All rights reserved. Use of this source code is governed by a |
3 // BSD-style license that can be found in the LICENSE file. | 3 // BSD-style license that can be found in the LICENSE file. |
4 | 4 |
5 library isolate.example.runner_pool; | 5 library isolate.example.runner_pool; |
6 | 6 |
7 import 'dart:async' show Future, Completer; | 7 import 'dart:async' show Future, Completer; |
8 | 8 |
9 import 'package:isolate/load_balancer.dart'; | 9 import 'package:isolate/load_balancer.dart'; |
10 import 'package:isolate/isolate_runner.dart'; | 10 import 'package:isolate/isolate_runner.dart'; |
(...skipping 10 matching lines...) Expand all Loading... |
21 sw.start(); | 21 sw.start(); |
22 // Then compute fib up to 42 with 2 isolates. | 22 // Then compute fib up to 42 with 2 isolates. |
23 parfib(N, 2).then((v2) { | 23 parfib(N, 2).then((v2) { |
24 var t2 = sw.elapsedMilliseconds; | 24 var t2 = sw.elapsedMilliseconds; |
25 sw.stop(); | 25 sw.stop(); |
26 print("fib#2(${N}) = ${v2[N]}, ms: $t2"); | 26 print("fib#2(${N}) = ${v2[N]}, ms: $t2"); |
27 }); | 27 }); |
28 }); | 28 }); |
29 } | 29 } |
30 | 30 |
31 // Compute fibonnacci 1..limit | 31 // Compute fibonacci 1..limit |
32 Future<List<int>> parfib(int limit, int parallelity) { | 32 Future<List<int>> parfib(int limit, int parallelity) { |
33 return LoadBalancer.create(parallelity, IsolateRunner.spawn).then( | 33 return LoadBalancer.create(parallelity, IsolateRunner.spawn).then( |
34 (LoadBalancer pool) { | 34 (LoadBalancer pool) { |
35 List<Future> fibs = new List(limit + 1); | 35 List<Future> fibs = new List(limit + 1); |
36 // Schedule all calls with exact load value and the heaviest task | 36 // Schedule all calls with exact load value and the heaviest task |
37 // assigned first. | 37 // assigned first. |
38 schedule(a, b, i) { | 38 schedule(a, b, i) { |
39 if (i < limit) { | 39 if (i < limit) { |
40 schedule(a + b, a, i + 1); | 40 schedule(a + b, a, i + 1); |
41 } | 41 } |
42 fibs[i] = pool.run(fib, i, load: a); | 42 fibs[i] = pool.run(fib, i, load: a); |
43 } | 43 } |
44 schedule(0, 1, 0); | 44 schedule(0, 1, 0); |
45 // And wait for them all to complete. | 45 // And wait for them all to complete. |
46 return Future.wait(fibs).whenComplete(pool.close); | 46 return Future.wait(fibs).whenComplete(pool.close); |
47 }); | 47 }); |
48 } | 48 } |
49 | 49 |
50 int computeFib(n) { | 50 int computeFib(n) { |
51 int result = fib(n); | 51 int result = fib(n); |
52 return result; | 52 return result; |
53 } | 53 } |
54 | 54 |
55 int fib(n) { | 55 int fib(n) { |
56 if (n < 2) return n; | 56 if (n < 2) return n; |
57 return fib(n - 1) + fib(n - 2); | 57 return fib(n - 1) + fib(n - 2); |
58 } | 58 } |
OLD | NEW |