Last active
December 17, 2015 23:39
-
-
Save Schoonology/5691289 to your computer and use it in GitHub Desktop.
An example of process.send vs worker.send.
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') | |
if (cluster.isMaster) { | |
console.log('Master started.') | |
// If we're a master process, we can listen on the 'fork' event to get Worker instances. | |
// We'll use it to communicate with that process. | |
cluster.on('fork', function (worker) { | |
// Now that we have a worker, we can listen on 'message' events that worker has sent. | |
// These messages are sent via process.send, below, and are received only by the master. | |
worker.on('message', function (msg) { | |
console.log('Master received %j from worker %s.', msg, worker.id) | |
}) | |
// If we want to send a message to a specific worker, we can use worker.send for that. | |
worker.send('Welcome!') | |
}) | |
// Now that's established, so let's fork a couple processes. | |
cluster.fork() | |
cluster.fork() | |
// NOTE: If we call process.send from the master process, that won't go to ANY worker. It | |
// will try to send the message to a parent process (of which there is none in this simple | |
// example. If this paragraph doesn't make sense, please leave a comment and I'll provide | |
// a separate example for this behaviour. | |
} else { | |
console.log('Worker started.') | |
// If we're a worker process, process.send can be used to communicate with the master process. | |
setInterval(function () { | |
process.send('Random message is random: ' + Math.random()) | |
}, 1000) | |
// Additionally, we can listen on the same 'message' event (but on process instead of on a | |
// Worker) to receive messages from the master. | |
process.on('message', function (msg) { | |
console.log('Worker received %j from the master.', msg) | |
}) | |
} | |
// So it's always .send() and .on('message'), but the master uses a Worker instance gotten from | |
// cluster.on('fork'), and the Worker uses the global process object. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment