Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is my counter variable safe for concurrent tasks?

Is below counter thread safe? I think that if I reach the sync function over async function, counter would work fine. Am I right? My explanation is function a() is sync function. It means that this function is atomic, that's why only one process works inside. it also means that counter get increased safely ?

    `var counter = 0;
     function a(){
     counter++
     }
     async function count(){
      //IO code;
      a();
     } 
     count();`
like image 861
Erdal76t Avatar asked Dec 07 '25 09:12

Erdal76t


1 Answers

Yes, the code is thread safe. Most values (except SharedArrayBuffers) can't be shared between threads, so they can't be accessed concurrently by two different threads.

As you mentioned "async functions": They run asynchronously in the sense that they might halt at specified points (basically when you await), and other code might run then, but all the other code will run till completion (so other code might only run inbetween when you use await).

An example of the same operation that could fail:

  counter = counter + await Promise.resolve(1);

This might fail as counter gets evaluated, then the promise gets awaited, other code might change counter in the meantime, and then you assign back to counter.

like image 148
Jonas Wilms Avatar answered Dec 09 '25 23:12

Jonas Wilms



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!