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,
myArray = ["foo","bar","baz","qux"];
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() {
}
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() {
if (done) {
console.log("Worker #" + cluster.worker + " completed the task!");
for (var id in cluster.workers) {
cluster.workers[id].kill();
}
}
}
, :)