Sunday 21 May 2017

Nodejs cluster: why blocking master will block workers too?

As you can see, in master(cluster.isMaster) while loop is blocking master, but why worker is also blocked?

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

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


  // background jobs start
  while(true) {
    console.log(123)
    sleep.sleep(1) // do_background_jobs()
  }
  // background jobs end


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

Here is logs:

Master 45476 is running
Worker 45479 started
Worker 45483 started
Worker 45482 started
Worker 45478 started

But netstat shows 8000 is closed. of cource curl fails.



via Sato

No comments:

Post a Comment