Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 81 lines (62 sloc) 2.222 kB
ab01f72 @xk 2nd commit, D day
authored
1 ## Sending events both ways between the main thread and a worker thread
2
3 This third example demonstrates how we can use events to communicate in both directions
4 between main thread and worker thread.
5
6 Like before, we create a worker thread and we define the fibonacci function:
7
8 ``` javascript
9 var Threads = require('threads_a_gogo');
10 var t = Threads.create();
11
12 function fibo(n) {
13 return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1;
14 }
15 ```
16
17 In the previous example we were running a loop that generates fibonacci numbers in the worker thread.
18 This is fine if the generator produces the number at a slower rate than the main thread can consume them
19 but it will hog memory if the main thread is too busy and cannot consume the data events fast enough.
20 We can improve this by controlling the flow with events in both directions.
21
22 The `thread` global variable that **threads_a_gogo** predefines in every worker thread is also an `EventEmitter`.
23 So we will use it to send events in the other direction, from the main thread to the worker thread.
24
25 Our modified generator does not use a loop any more. Instead, it generates numbers in response to `next` events
26 sent from the main thread. Here is the new generator:
27
28 ``` javascript
29 function generateFibos() {
30 var i = 1;
31 thread.on('next', function() {
32 thread.emit('data', i, fibo(i));
33 i++;
34 });
35 }
36 ```
37
38 From the main thread, we listen for the `data` events emitted by the worker thread.
39 Every time we get a `data` event from the worker thread, we print the result and we `emit` a
40 `next` event into the worker thread (stopping at 40):
41
42 ``` javascript
43 t.on('data', function(n, result) {
44 console.log('fibo(' + n + ') = ' + result);
45 if (n < 40) t.emit('next');
46 else console.log('bye!'), t.destroy();
47 });
48 ```
49
50 We now have all we need for our little ping-pong game. We load the two functions into the thread:
51
52 ``` javascript
53 t.eval(fibo);
54 t.eval(generateFibos);
55 ```
56
57 We start the generator in the worker thread:
58
59 ``` javascript
60 t.eval("generateFibos()");
61 ```
62
63 And we start the game by emitting the first `next` event:
64
65 ``` javascript
66 t.emit('next');
67 ```
68
69 ### Output
70
71 ```
72 fibo(1) = 1
73 fibo(2) = 2
74 fibo(3) = 3
75 fibo(4) = 5
76 ...
77 fibo(39) = 102334155
78 fibo(40) = 165580141
79 bye!
80 ```
Something went wrong with that request. Please try again.