Skip to content

Instantly share code, notes, and snippets.

@nanha
Created December 30, 2012 01:38
Show Gist options
  • Save nanha/4410453 to your computer and use it in GitHub Desktop.
Save nanha/4410453 to your computer and use it in GitHub Desktop.
cluster messaging
var cluster = require('cluster');
if (cluster.isWorker) {
console.log('Worker ' + process.pid + ' has started.');
// Send message to master process.
process.send({msgFromWorker: 'This is from worker ' + process.pid + '.'})
// Receive messages from the master process.
process.on('message', function(msg) {
console.log('Worker ' + process.pid + ' received message from master.', msg);
});
}
if (cluster.isMaster) {
console.log('Master ' + process.pid + ' has started.');
// Fork workers.
for (var i = 0; i < 2; i++) {
var worker = cluster.fork();
// 워커로부터 메세지가 수신되고,
// 워커의 pid 를 알 수 있습니다.
worker.on('message', function(msg) {
console.log('Master ' + process.pid + ' received message from worker ' + this.pid + '.', msg);
});
// 워커에 메세지를 보낼 때, pid 를 지정하여 보낼 수는 없습니다.
// broadcast 입니다.
worker.send({msgFromMaster: 'This is from master ' + process.pid + ' to worker ' + worker.pid + '.'});
}
// Be notified when worker processes die.
cluster.on('death', function(worker) {
console.log('Worker ' + worker.pid + ' died.');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment