Assuming the compiler will generate a single instruction that will increment x++
or decrement x--
, it will have the same value it had before the for loops were executed after both threads are done, which is 0.
Otherwise, let's take the following example:
x++:
1. MOV R1, x //register R1 receives x
2. INC R1 //register R1 is incremented
3. MOV x, R1 //store decremented x back to the memory
and
x--:
1. MOV R1, x //register R1 receives x
2. DEC R1 //register R1 is decremented
3. MOV x, R1 //store decremented x back to the memory
It is quite obvious now that if one thread looses the CPU after executing line 1, it will have a value which is not updated, which will lead to a race condition and the variable will then have any value beetwen -5 and +5 after both threads are done with their execution, as you pointed out, depending on the different order of execution that both threads can have.