Global variable safety when using i++ in Node.js

Viewed 260
var i = 1;

function er() {
   i++;
}

As far as I know, i++ operation includes three steps. Read-modify-write, when any event makes reading(at the first step), can any other modify the same i value? After reading, during modifying, can any other event get the modify access by context swithching? How contexts switching works?

2 Answers

Javascript (nodejs) is inherently single threaded. Everything happens in a callback, promise resolution, or timer / interval handler, or in the main program. Those things are not pre-emptible like they might be in a multithreaded environment.

There's no way in Javascript for a context switch or thread switch to generate a potential race condition messing up the integrity of i++ or any other read-modify-write operation.

The language doesn't need the interlocked increment hardware operation exposed by, for example, C#'s Interlocked.Increment() method.

As others have said, node.js is single threaded so there is no risk of a race condition from a context switch in this example. To answer your question about context switching, a context switch occurs when a scheduler decides to switch threads. Say you have two threads, i++ and i--, and the value of i is 10. The first thread may perform a load and modify i, but then may run out of its assigned cpu time. The context will be saved, and the second thread may execute its 3 steps. Now in memory, the value of i has been decremented to 9. Now the first thread resumes, loading its value of i from the context and executes its last step, the write to memory. Now the value of i in memory is 11. Depending on the order in which the threads are scheduled, the value of i in memory may end up being 9, 10, or 11. That is a race condition, a situation in which a shared resource is modified by two or more processes or threads, and the outcome depends on the order of execution. You can do some research on concurrent programming if you'd like to learn more!

Related