NiCk Newman
NiCk Newman

Reputation: 1776

Clustering Loop Confusion

My basic setup I have using the cluster module is: (I have 6 cores)

var cluster = require('cluster');
if (cluster.isMaster) {
  var numCPUs = require('os').cpus().length;
  for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
  }
}else{
//Code here
  console.time("Time: ");
  var obj = {'abcdef' : 1, 'qqq' : 13, '19' : [1, 2, 3, 4]};
  for(var i = 0; i < 500000; i++) {
            JSON.parse(JSON.stringify(obj));
    }
  console.timeEnd("Time: ");
}

If I were to run that test. It will output:

But... if I run that same exact test inside the cluster.isMaster block, it will output:

1) Why is my code being executed multiple times instead of once?

2) Since I have 6 cpu cores helping me run that test, shouldn't it run that code only once but perform the operation faster?

Upvotes: 0

Views: 882

Answers (1)

mscdex
mscdex

Reputation: 106696

  1. You're forking os.cpus().length separate processes. So if os.cpus().length === 6, then you should see 6 separate outputs (which is the case from the output you've posted).
  2. No, that's not how it works. Each process would be scheduled on a separate core. It's not about running it faster, but being able to do more processing in parallel.

Upvotes: 1

Related Questions