Skip to content

Instantly share code, notes, and snippets.

@NigelEarle
Created November 9, 2017 17:20
Show Gist options
  • Select an option

  • Save NigelEarle/edb4d54e1ca7edf1427ed3cf637bb602 to your computer and use it in GitHub Desktop.

Select an option

Save NigelEarle/edb4d54e1ca7edf1427ed3cf637bb602 to your computer and use it in GitHub Desktop.

Revisions

  1. NigelEarle created this gist Nov 9, 2017.
    26 changes: 26 additions & 0 deletions cluster.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    const cluster = require('cluster');
    const http = require('http');
    const numCPUs = require('os').cpus().length;


    if (cluster.isMaster) {
    console.log(`Master ${process.pid} is running`);

    // Fork workers.
    for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
    }

    cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
    });
    } else {
    // Workers can share any TCP connection
    // In this case it is an HTTP server
    http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello world\n');
    }).listen(8000);

    console.log(`Worker ${process.pid} started`);
    }