1 | /// !example
|
2 | /// ## Using the thread pool
|
3 | ///
|
4 | /// Our previous examples used a single worker thread, and thus only one processor core.
|
5 | /// If we want to take full advantage of multi-core processors, we need the ability to delegate
|
6 | /// expensive computations to a pool of theads. This example demonstrates the pool thread that comes
|
7 | /// bundled with Worker.
|
8 | ///
|
9 | /// First, we create a pool
|
10 | var Threads = require('webworker-threads');
|
11 | var pool = Threads.createPool(3);
|
12 | ///
|
13 | /// Then we load our fibonacci function in all the pool's threads:
|
14 | function fibo(n) {
|
15 | return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1;
|
16 | }
|
17 |
|
18 | pool.all.eval(fibo);
|
19 | /// Now, we can get fibonacci numbers from our pool
|
20 | ///
|
21 | /// We request them in reverse order, to show that longer computations (`fibo(40)`) run in
|
22 | /// parallel with shorter ones (`fibo(39)`, `fibo(38)`, ...). The results won't come out in strictly decreasing order.
|
23 | var remain = 11;
|
24 | for (var i = 40; i >= 30; i--) {
|
25 | // extra closure to get proper scoping on 'i'
|
26 | (function(i) {
|
27 | // dispatch each request to the first available thread
|
28 | pool.any.eval('fibo(' + i + ')', function(err, val) {
|
29 | console.log('fibo(' + i + ')=' + val);
|
30 | // destroy the pool when all results have been produced
|
31 | if (--remain == 0) console.log('bye!'), pool.destroy();
|
32 | });
|
33 | })(i);
|
34 | }
|
35 | /// ### Typical (*) Output
|
36 | ///
|
37 | /// (*) Execution is non-deterministic. So order may vary.
|
38 | ///
|
39 | /// ```
|
40 | /// fibo(38)=38
|
41 | /// fibo(39)=39
|
42 | /// fibo(37)=37
|
43 | /// fibo(35)=35
|
44 | /// fibo(36)=36
|
45 | /// fibo(33)=33
|
46 | /// fibo(34)=34
|
47 | /// fibo(31)=31
|
48 | /// fibo(32)=32
|
49 | /// fibo(30)=30
|
50 | /// fibo(40)=40
|
51 | /// bye!
|
52 | /// ``` |
\ | No newline at end of file |