Frage

I am using async.each like below:

async.each(students, plan(student, callback), function(err) {
.....
.....
});
plan(student, callback){
    ......
    ......
    commonDS[student.id] = student.name;
}

Here commonDS is a common data-structure across the function calls, so is there a race condition here?

War es hilfreich?

Lösung

Short answer: probably not.

Longer answer: Node.js is single threaded, so every synchronous block of code is atomic. In particular there are no threads and actually there is no concurrency (everything runs sequentially). Thus there are no race conditions on synchronous blocks of code.

Although there are race conditions in general. For example assume that you have your commonDS dict. Now you make an asynchronous request to load data X and you do commonDS[key] = X. Then for that X you make another asynchronous request (you load additional data) and you do commonDS[key].my_attr = Y. You have a race condition here. That's because you don't know which X object you alter (because you've chained asynchronous requests). You may end up with incorrectly filled object.

So in order to be sure we would need to know what happens in async.each (or generally everywhere else).

Note that there are no lock objects in Node.js so in case you need it you either implement it on your own (not difficult since Node.js is single-threaded) or use one of the existing libraries.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top