I have master and workers that calculate something in parallel.
How to sum up their results?
After each worker has done his job, he kill himself and 'res' variable has no value, so it's impossible to accumulate it to any variable.
if (cluster.isMaster) {
for (var i = 0; i < numCPUs; i++) {
const worker = cluster.fork();
worker.send({ mydata: array[i] });
}
} else {
process.on('message', (msg) => {
res = AnyFunction(msg.mydata, dx, f);
console.log('Result of ' + pid + ' worker: ' + res);
process.exit();
});
}
Is there any way?
Try the following:
if (cluster.isMaster) {
for (var i = 0; i < numCPUs; i++) {
const worker = cluster.fork();
worker.send({ mydata: array[i] });
let sum = 0;
worker.on('message', res => sum+=res);
}
} else {
process.on('message', (msg) => {
res = AnyFunction(msg.mydata, dx, f);
console.log('Result of ' + pid + ' worker: ' + res);
process.send(res);
process.exit();
});
}