var Worker = require('webworker-threads').Worker;
require('http').createServer(function (req,res) {
var fibo = new Worker(function() {
function fibo (n) {
return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1;
}
// which onmessage does this this refer to?
onmessage = function (event) { //reference 1
postMessage(fibo(event.data));
}
});
fibo.onmessage = function (event) { //reference 2
res.end('fib(40) = ' + event.data);
};
fibo.postMessage(40);
}).listen(port);
This is the code found as an example for the webworker class.
I was looking at the API and doen't seem to understand what reference 1 in the above code is referring to. Why does the postMessage(40) hit the inner onmessage function and not the fibo.onmessage function?
The main point to note here is that the onmessage() and postmessage() is used as message bearers between both the main thread and the worker thread. This can be confusing initially. So the flow goes like this
Create a worker thread .
var fibo= new Worker...
This will spawn another JavaScript thread in the node. It can run in parallel in the background and use all the available CPU cores. Otherwise in node due to its single threaded model, taking advantage of multiple CPU cores is not possible (hence worker threads is a good approach for handling CPU-bound tasks in node)
onmessage= function (event) { //reference 1
postMessage(fibo(event.data));
}
b) how to communicate back to the main thread once work is done- postMessage does this job.
postMessage(fibo(event.data));
In the main thread :- a. Call the worker thread and give it a task to execute -ie. using postmessage (By now you got the dance)
fibo.postMessage(40);
b. Define listener regarding the action to take once the worker thread finishes it job and responds back. ie. using onmessage.
fibo.onmessage = function (event) { //reference 2
res.end('fib(40) = ' + event.data);
};