Skip to content

Instantly share code, notes, and snippets.

@neilk
Last active December 16, 2015 06:19
Show Gist options
  • Save neilk/5391012 to your computer and use it in GitHub Desktop.
Save neilk/5391012 to your computer and use it in GitHub Desktop.
Attempt to use node-webworker threads
var Worker = require('webworker-threads').Worker;
var worker = new Worker('bin/testWorker.js');
var workerSend;
(function() {
var idCounter = 0;
var callbacks = {};
worker.onmessage = function(oEvent) {
var message = oEvent.data;
var _id = message._id;
delete message._id;
callbacks[_id](message);
delete callbacks[_id];
};
workerSend = function(message, callback) {
message._id = idCounter++;
callbacks[message._id] = callback;
worker.postMessage(message);
};
})();
exports.test = function(req, res, next) {
var label = req.param('label');
var n = parseInt(req.param('n'));
workerSend({ n: n }, function(message) {
var fibo = message.fibo;
res.send(label + " -> " + fibo + "\n");
});
};
function fibo(n) {
return (n > 1) ? fibo(n-1) + fibo(n-2) : 1;
}
onmessage = function(oEvent) {
var id = oEvent.data._id;
var f = fibo(oEvent.data.n);
postMessage({
_id: id,
fibo: f
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment