ruk·si

🟢 Node
Async Cluster

Updated at 2013-07-04 09:04
var cluster = require('cluster');
if (cluster.isMaster) {
    cluster.on('exit', function(worker) {
        console.log('ON MASTER: Worker ' + worker.id + ' has died');
    });

    var coreCount = require('os').cpus().length;
    for (var i = 0; i < coreCount; i++) {
        var worker = cluster.fork();
        worker.on('message', function(message) {
            if (message._queryId) {
                return;
            }
                console.log("ON MASTER: " + message);
        });
        worker.send('Hello!');
    }
} else {
    process.on('message', function(message) {
        console.log("ON CHILD:  " + message);
    });
    process.send('Good to see you!');
    setTimeout(function() {
        process.send('Goodbye!');
        process.exit();
    }, 1000);
}
ON CHILD:  Hello!
ON CHILD:  Hello!
ON MASTER: Good to see you!
ON MASTER: Good to see you!
ON MASTER: Good to see you!
ON CHILD:  Hello!
ON MASTER: Good to see you!
ON CHILD:  Hello!
ON MASTER: Goodbye!
ON MASTER: Worker 1 has died
ON MASTER: Goodbye!
ON MASTER: Worker 2 has died
ON MASTER: Goodbye!
ON MASTER: Worker 3 has died
ON MASTER: Goodbye!
ON MASTER: Worker 4 has died

Sources

  • Async JS