0

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?

Lucien
  • 776
  • 3
  • 12
  • 40
  • The clusters are separate processes. As such, they each live in their own process space and do not share any variables. A common way to share data is via an out-of-process in memory database such as redis that let's all clusters access the same shared data. – jfriend00 Apr 08 '17 at 07:31
  • If you examine the code for cluster [here on Github](https://github.com/nodejs/node/blob/master/lib/internal/cluster/master.js#L162), you will see that it ends up calling `child_process.fork()` with a custom environment. The actual call to `child_process.fork()` is [here](https://github.com/nodejs/node/blob/master/lib/internal/cluster/master.js#L131). The beauty of an open source system is you can ultimately answer any question by examining the code yourself. – jfriend00 Apr 08 '17 at 07:37

0 Answers0