Node.js Master-Worker communication. Master fires an event but only one worker listens. Need all workers to listen

时间:2015-09-30 23:21:34

标签: javascript node.js cluster-computing eventemitter

In the following code I have a worker send a message to the master (through process.send from a different file) to tell the master to inform all workers to execute a function, but only the worker which is sending the message executes the function. How can I have all the workers execute the function?

var listener = function() {
    doSomeThing;

};

if (cluster.isMaster) {
    numCpu = require('os').cpus().length;

    for (var i = 0; i < numCpu; i += 1) {
        var worker = cluster.fork();

        worker.on('message', function(msg)) {
            if(msg.fromWorker) {
               console.log('Worker(' + worker.id + ') to Master: ' +  msg.fromWorker);
               worker.send({fromMaster: 'New instructions, immediately perform function.'});
               eventEmitter.on('someThing', listener);
            }
        });
//Code to run if in worker process.
} else {
process.on('message', function(msg) {
    if(msg.fromMaster) {
        eventEmitter.emit('someThing');
    }
});

0 个答案:

没有答案