algorithm - 如何积累异步数据?

标签 algorithm node.js design-patterns asynchronous

我想汇总异步生成的数据(在 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/

相关文章:

algorithm - 调度生命的调度算法

node.js - 跨水平服务器计算 socket.io 用户

javascript - 将 html2pdf 生成的 pdf 发送回服务器

node.js - 将 Travis-CI 用于 Node.js 项目

c++ - 我的组件需要访问者吗?

c++ - 与 2,3 和更多整数的子集和相关的想法

python - 如何修复我的遍历对角矩阵代码(替代版本)?

design-patterns - 具有作业亲和性的作业队列

amazon-web-services - 批量工作负载与微服务调用

java - 生成一些数字范围内所有排列的序列