本文介绍了JavaScript中的数据竞赛?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我运行这段代码.

var score = 0;
for (var i = 0; i < arbitrary_length; i++) {
     async_task(i, function() { score++; }); // increment callback function
}

从理论上讲,我理解这会引起数据争用,并且试图同时增加两个线程可能会导致一个增量,但是,已知nodejs(和javascript)是单线程的.我是否可以保证score的最终值将等于random_length?

In theory I understand that this presents a data race and two threads trying to increment at the same time may result in a single increment, however, nodejs(and javascript) are known to be single threaded. Am I guaranteed that the final value of score will be equal to arbitrary_length?

推荐答案

节点使用事件循环.您可以将其视为一个队列.因此,我们可以假设,您的for循环将function() { score++; }回调arbitrary_length时间放在此队列中.之后,js引擎逐个运行这些引擎,并每次增加score.是的唯一的例外是未调用回调或从其他位置访问score变量.

Node uses an event loop. You can think of this as a queue. So we can assume, that your for loop puts the function() { score++; } callback arbitrary_length times on this queue. After that the js engine runs these one by one and increase score each time. So yes. The only exception if a callback is not called or the score variable is accessed from somewhere else.

实际上,您可以使用此模式并行执行任务,收集结果并在完成每个任务后调用一个回调.

Actually you can use this pattern to do tasks parallel, collect the results and call a single callback when every task is done.

var results = [];
for (var i = 0; i < arbitrary_length; i++) {
     async_task(i, function(result) {
          results.push(result);
          if (results.length == arbitrary_length)
               tasksDone(results);
     });
}

这篇关于JavaScript中的数据竞赛?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:21