1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

if you are telling that nodejs is single threaded than how async works. it says parallel(tasks, [callback]) Run the tasks array of functions in parallel.
@Trying Excelent question. Actually it does not run them in parallel (since as I said: it is technically impossible). It just runs them and tracks when they finish. The description is incorrect. Try putting synchronous functions like function(clb) { console.log(1); clb(); } inside and see what happens (they will always fire in the same order). However you will most likely use asynchronous functions with .parallel and so you will see the illusion of parallelism (I/O in Node.js happens parallely, you don't wait for a request to finish - you will be notified and a callback will fire).
@Trying Also read this article: debuggable.com/posts/… I'm not as good as that guy is at explaining things. However he does make a mistake in believing that there are no race conditions in Node.js. It's just that they are a lot harder to create.
+1 Thanks for your answer. If it's an excellent question don't i deserve a +1 :; .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.