Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 304
Erdal76t Avatar asked Jun 29 '26 04:06

Erdal76t


1 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.

like image 171
O. Jones Avatar answered Jun 30 '26 18:06

O. Jones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!