Killing node.js workers after function execution

I am a complete newbie node.js who just started doing this. I have a piece of code that performs a function that processes strings on all processor cores, and I want to determine which of the workers completed the function first with this id, and after that it will kill every worker (or just exit node).

Here is the simplified code of my program:

var cluster = require('cluster'),
    cpus = require("os").cpus().length, // 4 cores
    myArray = ["foo","bar","baz","qux"]; // 1 string per core

if (cluster.isMaster) {
    for (var i = 0; i < cpus; i++) {
        var worker = cluster.fork();
    }
    cluster.on('exit', function(worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
    });
} else if (cluster.isWorker) {
    computeString(myArray[cluster.worker.id]);
}

function computeString() {
    // Code to compute...
}

This code works, and the computeString () function ends much faster than executing it outside

else if (cluster.isWorker) {}

So the problem is that after one worker / process terminates this function, node waits until each process has completed its work and terminated after that, each process will remain idle until I press ctrl + c.

My approach:

function computeString() {
    // Code to compute...
    if (done) {
         console.log("Worker #" + cluster.worker + " completed the task!");
         for (var id in cluster.workers) {
            cluster.workers[id].kill();
         }
     }
}

, :)

+5
1

, , ?

...
cluster.on('exit', function(worker, code, signal) {
  console.log('worker ' + worker.process.pid + ' died');
  // kill the other workers.
  for (var id in cluster.workers) {
    cluster.workers[id].kill();
  }
  // exit the master process
  process.exit(0);
});
...
function computeString() {
  // Code to compute...
  if (done) {
    process.exit(0); // exit the worker process cleanly, triggering the 'exit' event
  }
};
+7

All Articles