I ++ is divided into three phases:
Memory to register
Register auto-Increment
Write back memory
All three stages can be interrupted and separated.
I ++ executes 100 times in two threads respectively. What are the maximum and minimum values?
I ++ only needs to execute one command and cannot guarantee that multiple threads I ++ can operate on the same I to get the correct result. Because of the Register, multiple CPUs correspond to multiple registers. It takes at least three steps to copy I from memory to register, then ++, And then I to memory. In this sense, I ++ is not atomic.
In this case, the execution steps of the two threads are as follows:
1. Thread a executes I ++ for the first time and extracts the I in the memory. The value is 0, and 1 is added after it is stored in the register. At this time, the value in the cpu1 register is 1, and the value in the memory is 0;
2. Thread B executes I ++ for the first time and extracts the I in the memory. The value is 0, and 1 is added after it is stored in the register. At this time, the value in the cpu2 register is 1 and the value in the memory is 0;
3. Thread a continues to execute 99th times I ++ and puts the value back into the memory. In this case, the value of the Register in cpu1 is 99, and the value of memory is 99;
4. Thread B continues to execute the first I ++ (from the register, take 0), and puts the value back into the memory. At this time, the register value in cpu2 is 1, and the memory value is 1.(Flushed all results);
5. Thread a executes I ++ 100th times, retrieves the value in memory from the Register of cpu1, and Adds 1 to it. In this case, the value in the register of cpu1 is 2 and the value in memory is 1;
6. Thread B executes all the operations and puts them back into the memory. At this time, the cpu2 register value is 100, and the memory value is 100;
7. Thread a executes the last part of the 100 operation (from the register, take 2), put the register value in cpu1 back into the memory, and the memory value is 2(Flushed all results);
8. End!
Therefore, the final result of this question can be obtained. The minimum value is 2 and the maximum value is 200.
I ++ atomic operations