Friday 7 April 2017

Node's Cluster Fork

I don't understand how clusters work in Node.

The snippet below is example code from Node's docs.

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`);
}

I'd like to know exactly what happens at cluster.fork(). Does it copy over any variables to the forked processes? If I declared an object before forking, would both threads access it? Is it possible to assign tasks to a thread manually or does Node have to do it?



via Lolums

No comments:

Post a Comment