Search code examples
node.jsconcurrencycritical-section

Correct way to implement a critical section in NodeJs


I have an operation/task that I need to run, which is triggered by an event getting fired (I don't think this last thing is really important).

Thing is, this task is composed of several io operations, network calls mostly. Also, I would like to run this task atomically, start to end, one at the time, newer tasks should not start until the current one finishes.

I would normally do this using a critical section of some kind, but I don't think there's such a concept in js or the node base lib. How do you suggest I should handle a case like this?

thanks

EDIT: I've seen the "critical sections are not needed, this is single threaded" opinion several times in different posts and I think that is only partially true, it only applies to synchronous actions.

Suppose the typical scenario for which critical sections are used, you need to do 2 things A) check for the validity of a condition, B) apply an action only if A is either true or false, an action that would flip the condition. You don't want 2 threads to arrive to the conclusion that A is false at the same time, and that B should be done, so you wrap A and B in a critical section to make them atomic. In node.js, if A in synchronous then you are fine, no other thread will be running and you can do B safely. But if A is async, before it's callback fires, another event for A might show up on the event queue, before the first one get's it's B executed.


Solution

  • As mscdex noted a queue would be preferable, Async has queue() that would be able to handle the scenario you described. To guarantee the 'critical section' feel just set concurrency: 1 for the queue.