Last active
December 16, 2015 06:19
-
-
Save neilk/5391012 to your computer and use it in GitHub Desktop.
Attempt to use node-webworker threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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