Skip to content

Instantly share code, notes, and snippets.

@elgs
Last active August 29, 2015 13:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elgs/9107314 to your computer and use it in GitHub Desktop.
Save elgs/9107314 to your computer and use it in GitHub Desktop.
Nodejs cluster
var cluster = require('cluster');
var http = require('http');
var numWorkers = 2;

if (cluster.isMaster) {
    // Fork worker.
    for (var i = 0; i < numWorkers; ++i) {
        console.log('master: about to fork a worker');
        cluster.fork();
    }

    cluster.on('fork', function (worker) {
        console.log('master: fork event (worker ' + worker.id + ')');
    });

    cluster.on('online', function (worker) {
        console.log('master: online event (worker ' + worker.id + ')');
    });

    cluster.on('listening', function (worker, address) {
        console.log('master: listening event (worker ' + worker.id + ', pid ' + worker.process.pid + ', ' + address.address + ':' + address.port + ')');
    });

    cluster.on('exit', function (worker, code, signal) {
        console.log('master: exit event (worker ' + worker.id + ')');
    });
} else {
    console.log('worker: worker #' + cluster.worker.id + ' ready!');
    var count = 0;
    // Workers can share any TCP connection
    // In this case its an HTTP server
    http.createServer(function (req, res) {
        res.writeHead(200);
        ++count;
        console.log('Worker #' + cluster.worker.id + ' is incrementing count to ' + count);
        res.end('hello world from worker #' + cluster.worker.id + ' (pid ' + cluster.worker.process.pid + ') with count = ' + count + '\n');
        if (count === 3) {
            cluster.worker.destroy();
        }
    }).listen(process.env.PORT, process.env.IP);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment