int global = 0;//thread 1for (int i = 0; i < ++i) Global-= 1;//thread 2for (int i = 0; i < ++i) global + = 1;
What is the possible value of global after (multiple possible)?
The problem is that global variables the add and subtract operations are not atomic operations and may be interrupted during the addition and subtraction process, resulting in a different result than expected. The above global plus and minus operations are compiled as follows
Windows plus operation mov eax,dword ptr [globle (10a9148h)] Add eax,1 mov dword ptr [Globle (10a9148h)],eax; windows down operation mov Eax,dwor D ptr [Globle (10a9148h)] Sub eax,1 mov dword ptr [Globle (10a9148h)],eax; Linux under Add Operation MOVL Global,%EAXADDL $,%EAXMOVL%ea X, global;linux down Operation MOVL Global,%eaxsubl $,%eaxmovl%eax, Global
It can be seen that both the add and subtract are loaded into the EAX by the value of global, then the EAX is added minus 1, and then the final write back to global. If the value of thread 1 's global is just loaded into eax, thread 2 gets the execution right and there is a problem. See the example below.
Assume that the global value is 5 before the operation.
Thread 1 Thread 2
MOVL Global,%eax;global value is 5,%eax value of 5
Addl $1,%eax;%eax value is 6
------Now thread 2 gets execute permission--------->
MOVL Global,%eax;global value is 5,%eax value of 5
Subl $1,%eax;%eax value is 4
MOVL%eax,global;%eax value is 4,global value of 4
<--------execution right back to thread 1--------------
MOVL%eax,global;%eax value is 4,global value of 4
As can be seen from the above example, the result is not that we expect the value of global to remain the original value after 1 minus 1, but from 5 to 4. This is the possible problem of non-atomic operation under multithreading.
So the title global output is not 01 possible. Global add-and-subtract operations are likely to fail, so global results should be distributed between 10 and 10.
Need to understand for hardware, although the operation of a value of global, but only one register, if the lock is not used, two threads read the same register. This causes the value of the global value to be many kinds of
Multi-threaded Read global variables (how many values occur in a lock-free State)