Search code examples
node.jsevent-loop

Increment counter sequentially in Node.js


I want to know how can I ensure that I increment counter correctly in Node.js environment.

If I understand correctly, async functions are processed by non-main threads that are instantiated by 4 libuv library threads, and the callbacks are executed by the main thread (event loop).

If above is true, then below code can result in incorrect updates to counter because f1() & f2() can try to update counter at the same time giving a final result of 1 instead of 2.

How do I rewrite the code below to ensure correct update to counter?

var counter = 0

async function f1() {
  // do something
  
  counter++
}

async function f2() {
  // do something
  
  counter++
}
f1()
f2()

Solution

  • No, there is no way that f1 and f2 do access the same counter variable at the same time, so the "final" result will be 2.
    However which of f1 or f2 would have set it to 1 or 2 is unsure.

    Async functions are still ran by the one and only JS processing, not by background threads. Maybe they will themselves be waiting for some tasks that are processed by other processes, depending on the API calls they'll make, but the JS part is still ran by the one and only JS processing that has access to the counter variable.

    So there is no risk of clashing here.

    The only case where you could have such an issue is with SharedArrayBuffer objects, when shared across different JS contexts (e.g with web workers). Though for this case we have Atomics.
    But here the counter variable is not a SharedArrayBuffer, and can't be shared across contexts. So once again, when f1 and f2 will both have resolved in an undetermined order, counter will hold the value 2.