汇总 Worker NodeJS 的值

Sum up values from workers NodeJS

我有 master 和 workers 并行计算一些东西。

如何总结他们的成果?

每个工人完成工作后,他自杀了,'res'变量没有值,所以不可能累加到任何变量。

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

有什么办法吗?

尝试以下操作:

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