0

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?

  • I guess you should be receiving promises from each worker when they are assigned with a task. Place them in an array and use `Promise.all(myWorkerPromisesArray)`. – Redu Sep 30 '17 at 11:46
  • Just make the workers send a message of the result before killing themselves. Then catch those messages in the event listener you have above and accumulate your result. – ibrahim mahrir Sep 30 '17 at 12:07

1 Answers1

0

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();
    });
}
Jonah
  • 1,495
  • 4
  • 17
  • 32