Skip to content

Instantly share code, notes, and snippets.

@AndreasMadsen
Created February 1, 2012 22:32
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 AndreasMadsen/1719892 to your computer and use it in GitHub Desktop.
Save AndreasMadsen/1719892 to your computer and use it in GitHub Desktop.
> node test.js
worker ID:1 got message. message-1
worker ID:0 got message. message-1
worker ID:1 got message. message-2
worker ID:0 got message. message-2
var cluster = require('cluster');
var http = require('http');
var numReqs = 0;
if (cluster.isMaster) {
var workers = {};
// Fork two workers onto their own thread
for (var i = 0; i < 2; i++) {
var worker = cluster.fork();
workers[i] = worker;
(function (i) {
worker.on('message', function(msg) {
// is internal
if (msg.cmd) return;
console.log('worker ID:' + i + ' got message.', msg);
});
})(i);
}
}
else {
// If the worker is not the master process, run it as an HTTP server
http.Server(function(req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(process.env.PORT || 8080, "0.0.0.0");
process.send('message-1');
setTimeout(function () {
process.send('message-2');
}, 500);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment