Created
December 17, 2013 18:19
-
-
Save nemtsov/8009958 to your computer and use it in GitHub Desktop.
A naïve way to broadcast a message to all workers in a cluster from another worker.
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 cluster = require('cluster'); | |
var http = require('http'); | |
var numCPUs = 3; | |
var workers = []; | |
if (cluster.isMaster) { | |
for (var i = 0; i < numCPUs; i++) { | |
workers.push(cluster.fork()); | |
} | |
// rebroadcast a message from a | |
// single worker to all other workers | |
workers.forEach(function (w, i) { | |
w.on('message', function (msg) { | |
if ('broadcast' !== msg.type) return; | |
workers.forEach(function (w, j) { | |
if (i === j) return; | |
w.send(msg.body); | |
}); | |
}); | |
}); | |
cluster.on('exit', function(worker, code, signal) { | |
console.log('worker ' + worker.process.pid + ' died'); | |
}); | |
} else { | |
process.on('message', function (msg) { | |
console.log('[%s] %s', process.pid, msg); | |
}); | |
// Workers can share any TCP connection | |
// In this case its a HTTP server | |
http.createServer(function(req, res) { | |
// process.send will not be available | |
// if running this worker standalone | |
if (process.send) { | |
process.send({type: 'broadcast', body: 'hello'}); | |
} | |
res.writeHead(200); | |
res.end('ok\n'); | |
}).listen(8000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment