杀死node.js工作完成后的function
我是一个刚刚开始修补的node.js新手。 我有一段代码执行一个处理所有cpu核心上的string的函数,我想确定哪个工作者先用id完成了函数,然后杀掉每个工作者(或者只是退出节点)。
以下是我的程序的简化代码:
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()函数的完成速度要比执行它之外的要快得多
else if (cluster.isWorker) {}
所以问题是在一个worker / process完成这个函数之后,node等待每个进程完成他们的工作,并且在这些之后不会终止,每个进程都保持空闲直到我按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(); } } }
但是因为我在这里问,显然不工作:)
所以当第一个工人做完工作的时候,你想杀掉所有的工人吗?
... 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 } };