bilalba bilalba - 3 months ago 19
Javascript Question

Data Races in JavaScript?

Lets assume I run this piece of code.

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

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?


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) {
          if (results.length == arbitrary_length)