Allows me to use the following code:
var shared = 100; function workWithIt(){ shared += 100; } setTimeout(workWithIt, 500); setTimeout(workWithIt, 500);
Ideally, this piece of code should add 200 to the shared variable, which after that will be 300.
But, as I know from c , there may be some consequences if the operation + = is divided into several commands.
Suppose this is an executable function order:
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 now has a value of 200.
This can happen in many programming languages, such as c, C ++, java, C #, ... - but can it happen in Javascript too?
Or, more generally, how does Javascript handle its threads when it switches between threads, and are there any built-in methods that can be used to handle race conditions?
javascript multithreading synchronization thread-safety race-condition
maja Jan 30 '14 at 21:02 2014-01-30 21:02
source share