Skip to content

Instantly share code, notes, and snippets.

@PaulGuo
Last active November 16, 2019 23:35
Show Gist options
  • Save PaulGuo/e9fdbe18694cff9b1643 to your computer and use it in GitHub Desktop.
Save PaulGuo/e9fdbe18694cff9b1643 to your computer and use it in GitHub Desktop.

fork_mode.js

var child_process = require('child_process');
var cpus = require('os').cpus();
var net = require('net');
var tcpSrv = net.createServer();

tcpSrv.listen(8000, function() {
    for (var i = 1; i <= cpus.length; i++) {
        var worker = child_process.fork('worker.js');
        worker.send(i, tcpSrv._handle);
    }

    tcpSrv.close();
});

worker.js

var http = require('http');

process.on('message', function(id, handle) {
    console.log('process %s init', id);

    http.createServer(function(req, res) {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Worker ' + id);
    }).listen(handle);
});

cluster_mode.js

var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
    // Fork workers.
    for (var i = 1; i <= numCPUs; i++) {
        cluster.fork();
        console.log('process %s init', i);
    }

    cluster.on('exit', function(worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
    });
} else {
    // Workers can share any TCP connection
    // In this case its a HTTP server
    http.createServer(function(req, res) {
        res.writeHead(200);
        res.end('Worker ' + cluster.worker.id);
    }).listen(8000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment