Skip to content

Instantly share code, notes, and snippets.

@mdickin
Last active April 30, 2016 04:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdickin/03e67c263b6044848ae90e6aca0c2d6d to your computer and use it in GitHub Desktop.
Save mdickin/03e67c263b6044848ae90e6aca0c2d6d to your computer and use it in GitHub Desktop.
/*
Up front scenario: run "node testCluster.js upFront"
On demand scenario: run "node testCluster.js ondemand"
*/
var cluster = require("cluster")
var os = require("os")
module.exports = {
spawnUpFront: spawnUpFront,
spawnOnDemand: spawnOnDemand
}
var _data = []
var _startDt
if (cluster.isWorker)
{
return runWorker(cluster.worker)
}
if (process.argv[2] == "ondemand") {
spawnOnDemand()
}
else {
spawnUpFront()
}
function spawnUpFront() {
populateData(false);
subscribe()
for (var i = 0; i < os.cpus().length; i++) {
cluster.fork();
}
}
function spawnOnDemand() {
populateData(true);
subscribe()
cluster.on("exit", function () {
if (_data.length > 0) cluster.fork()
});
for (var i = 0; i < os.cpus().length; i++) {
cluster.fork();
}
}
function populateData(killSelf) {
_startDt = Date.now()
for (var i = 0; i < 5000; i++) {
_data.push(killSelf);
}
}
function subscribe() {
/* Fix for Node.js v6, change callback signature to "function (worker, msg)" */
cluster.on("message", function (msg) {
var data = _data.pop();
if (data == undefined) {
console.log("Elapsed: %s ms", Date.now() - _startDt)
process.exit()
}
console.log(_data.length)
cluster.workers[msg.workerid].send(data)
})
}
function runWorker(worker) {
worker.on("message", handleMessage);
worker.send({workerid: worker.id})
worker.send({workerid: worker.id})
function handleMessage(shouldExit) {
if (shouldExit == undefined) process.exit()
setTimeout(function () {
if (shouldExit == true) process.exit()
worker.send({workerid: worker.id})
}, 30)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment