我想汇总异步生成的数据(在 node.js 中)。 您将如何以线程安全的方式执行此操作?
例如,
function test(){
var accumulator = 0;
for(int i= 0; i<100; i++){
// non blocking function producing value
getasyncdata(i, function(value){
// this is spread over 3 lines to simulate non atomic operation.
tmp = accumulator;
tmp = tmp + value;
accumulator = tmp;
});
}
console.log(accumulator);
}
我看到它的方式 getdata 回调将被并行调用 100 次...并且累加器很可能不会是 100 个值的总和,因为回调不是原子的(或者是?)...
你怎么看?
最佳答案
您可以使用一个函数来检查是否有任何作业正在运行,然后在我们完成后打印出来。例如:
function test(){
var accumulator = 0, pendingOps = 0;
for(int i= 0; i<100; i++){
// non blocking function producing value
pendingOps++;
getasyncdata(i, function(value){
// this is spread over 3 lines to simulate non atomic operation.
tmp = accumulator;
tmp = tmp + value;
accumulator = tmp;
printIfFinished();
});
function printIfFinished() {
pendingOps--;
if(pendingOps) == 0 {
console.log(accumulator);
}
}
}
}
有很多控制流库可以帮助您做到这一点,其中两个是比较流行的:
关于algorithm - 如何积累异步数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20524962/