1 | /// !example
|
2 | /// ## Sending events from a worker thread
|
3 | ///
|
4 | /// This second example demonstrates how we can use events to communicate from the worker
|
5 | /// thread to the main thread.
|
6 | ///
|
7 | /// Like before, we create a thread and we define the fibonacci function:
|
8 | var Threads = require('webworker-threads');
|
9 | var t = Threads.create();
|
10 |
|
11 | function fibo(n) {
|
12 | return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1;
|
13 | }
|
14 | /// Instead of running a single fibonacci computation in the worker thread, we are going to execute a function
|
15 | /// that computes all fibonacci numbers and emits a `data` event for every number it generates.
|
16 | ///
|
17 | /// This function runs inside the worker thread so it does not see the `t` variable which belongs to the
|
18 | /// main thread. But **webworker-threads** sets up a global `thread` variable that the worker thread can use to
|
19 | /// send events to the main thread.
|
20 | ///
|
21 | /// Here is our fibonacci generator:
|
22 | function generateFibos(max) {
|
23 | for (var i = 1; i <= max; i++) {
|
24 | thread.emit("data", i, fibo(i));
|
25 | }
|
26 | }
|
27 | /// Note: this is obviously a very inefficient algorithm to generate the sequence of fibonacci numbers.
|
28 | ///
|
29 | /// Inside the main thread, we set up an event listener for the `data` events emitted by the
|
30 | /// worker thread:
|
31 | t.on('data', function(n, result) {
|
32 | console.log('fibo(' + n + ') = ' + result);
|
33 | })
|
34 | /// Now, we are ready to go. We load the two functions into the worker thread
|
35 | t.eval(fibo);
|
36 | t.eval(generateFibos);
|
37 | /// And we run the generator with a callback that will execute when the generator returns from its loop:
|
38 | t.eval("generateFibos(40)", function(err, result) {
|
39 | if (err) throw err;
|
40 | console.log("generator is done!");
|
41 | t.destroy();
|
42 | });
|
43 | /// ### Output
|
44 | ///
|
45 | /// ```
|
46 | /// fibo(1) = 1
|
47 | /// fibo(2) = 2
|
48 | /// fibo(3) = 3
|
49 | /// fibo(4) = 5
|
50 | /// ...
|
51 | /// fibo(39) = 102334155
|
52 | /// fibo(40) = 165580141
|
53 | /// generator is done!
|
54 | /// ``` |
\ | No newline at end of file |