Preet Saxena
Preet Saxena

Reputation: 127

Node JS Cluster to use 4 core of cpu at the same time

Server code

module.exports = function(cluster){
    let express = require('express')
    let app = express()
    app.get('/',function(req, res){

      console.log('Worker %d started!'+new Date(), cluster.worker.id);

      sleep(60000)

      for(var i = 0; i < 999999999; i++) {}

      res.end('Hello from Worker ' + cluster.worker.id);
      console.log('Worker %d returned!'+new Date(), cluster.worker.id);
    });
    app.listen(8080,function(){
      console.log('Application started! Worker %d started!, process %d', cluster.worker.id, cluster.worker.process.pid);
    });
    function sleep(miliseconds) {
        var currentTime = new Date().getTime();

        while (currentTime + miliseconds >= new Date().getTime()) {
        }
     }
  }

Cluster Code

let cluster = require('cluster');
let app = require('./index');
cluster.schedulingPolicy = cluster.SCHED_RR;
if(cluster.isMaster){
  let cpuCount = require('os').cpus().length;
  for (var i = 0; i < cpuCount; i += 1) {
    cluster.fork();
  }

  cluster.on('exit', function() {
    cluster.fork();
  });
}else{
  app(cluster);
}
cluster.on('fork', function(worker) {
console.log('forked -> Worker %d', worker.id);
});

-When I am hitting multiple API on default express port 8080 then it is using only one core of CPU where it waits for the process of the first hit and then the next request will be executed. -Why Cluster not using the other core of CPU to process 4(for quad-core CPU) request parallelly.

Upvotes: 0

Views: 183

Answers (1)

Preet Saxena
Preet Saxena

Reputation: 127

Rather than running a script from a single tab, run it with the multiple command tabs, all the CPU of your computer will be utilized, you can check them in system monitor.

Upvotes: 1

Related Questions