Killing node.js workers after function is done

11,959

So you want to kill all workers when the first worker has done its work?

...
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
  }
};
Share:
11,959

Related videos on Youtube

fnx
Author by

fnx

Updated on September 29, 2022

Comments

  • fnx
    fnx over 1 year

    I'm a total node.js newbie who's just started tinkering with it. I have a piece of code that executes a function that processes strings on all cpu cores, and I wish to determine which worker completed the function first by it's id, and after that kill every worker (or just exit node).

    Here's 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 finishes much faster than executing it outside the

    else if (cluster.isWorker) {}
    

    So the problem is that after one worker/process completes the function, node waits until every process has done their job and doesn't terminate after those either, every process stay idle until I hit ctrl+c.

    My approach was:

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

    But since I'm asking here, it obviously doesn't work :)

  • mithra
    mithra about 8 years
    my case i want to kill and restart worker one by one when a condition becomes true, please shed any light on that
  • robertklep
    robertklep about 8 years
    @mithra this depends on the exact use case. Perhaps create a new question outlining exactly what it is that you're trying to accomplish.