Killing node.js workers after function is done

烈酒焚心 提交于 2021-02-20 06:53:53

问题


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 :)


回答1:


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


来源:https://stackoverflow.com/questions/15548943/killing-node-js-workers-after-function-is-done

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!