Lets asume I have a code like the following:
var shared = 100;
function workWithIt(){
shared += 100;
}
setTimeout(workWithIt, 500);
setTimeout(workWithIt, 500);
Ideally, this piece of code should add 200 to the variable shared
, which is 300 afterwards.
But, as I know from c
, there can be some implications, if the operation += is split into multiple commands.
Lets say, that this is the execution-order of the function:
setTimeout() --> create Thread A
setTimeout() --> create Thread B
wait 500ms
**Thread A** | **Thread B**
--------------------------------+---------------------------------
var tmpA = shared; //100 |
| var tmpB = shared; //100
| tmpB = tmpB+100; //tmpB=200
| shared = tmpB;
tmpA = tmpA+100; //tmpA=200 |
shared = tmpA; |
In this case, shared
has now the value 200.
This can happen in many programming-languages like c, c++, java, c#, ... - but can it also happen in Javascript?
Or more generally speaking: How does Javascript handle its threads, when does it switch between threads, and are there built-in methods, that can be used for handling race-conditions?