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