功能完成后杀死 node.js 工人 [英] Killing node.js workers after function is done

查看:52
本文介绍了功能完成后杀死 node.js 工人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个完全的 node.js 新手,刚刚开始修补它.我有一段代码,它执行一个处理所有 cpu 内核上的字符串的函数,我希望通过它的 id 来确定哪个工作人员首先完成了该功能,然后杀死每个工作人员(或只是退出节点).

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

此代码有效,并且computeString() 函数完成速度比在外部执行它快得多

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

else if (cluster.isWorker) {}

所以问题是,在一个工人/进程完成该功能后,节点会等到每个进程完成其工作并且在完成这些工作之后也不会终止,每个进程都保持空闲状态,直到我按下 ctrl+c.

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.

我的方法是:

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

推荐答案

所以你想在第一个工人完成工作后杀死所有工人?

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

这篇关于功能完成后杀死 node.js 工人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆