Simple understanding of CAS
1. What is CAS?
CAS (Compare And Swap): compare and exchange. It is a CPU instruction that can perform compare and exchange operations atomically without locking.
CAS has 3 operands:
- The memory value that needs to be read and written: V
- Old expected value: A
- Update value: B
The specific operation process is as follows:
If and only if the value of V (in memory) is equal to A (expected value), CAS updates the value of V with B (new value) in an atomic way, otherwise no update is performed.
2. The execution process of CAS
You may ask: Why do you need to design an expected value A and V for comparison instead of directly exchanging V and B?
Because only in this way can the correct operation be completed in a concurrent environment, let's imagine this scenario:
Thread 1 and thread 2 want to jointly complete the self-increment operation of the variable n. Their goal is to increase n from 1 to 100, but we know that either thread is not safe, and then n++
CAS ++n
will come into play.
(1) At the initial moment, we set n to 1 initially, then the expected value A is also 1, because it is an auto-increment operation, so the update value B is set to A+1.
(2) Assume that thread 1 performs the self-increment operation of CAS first, and finds 预期值A
that the 内存值V
sum is equal, so B
it is used to update the value of V. as follows:
(3) Then thread 2 performs the CAS operation, but finds that V is 2 and A is 1, A和V不相等
so it cannot be updated, but enters a loop to reacquire the value of V and assign it to A.
(4) Thread 2 next performs the second CAS operation, 发现A和V相等
, then updates V to 3. as follows:
(5) Then it is thread 1's turn. It first finds that it cannot be updated, and then assigns the current memory value to A. After A and V are equal, it continues to complete the auto-increment operation. Repeatedly.
So far, the two threads have achieved concurrent self-increment of n. This process does not require locking, but also achieves concurrency safety.
3. Defects of CAS
(1) ABA problem
In a concurrent environment, assuming that the initial condition is A, when a thread modifies it again, it is found that it is still A, and the modification is successful; but before that, it may be modified to B and then back to A, which we do not know.
(2) The cycle time overhead is large
When a thread is unsuccessfully updated, the thread will enter the spin state, and it will continue to try. If the update fails for a long time, it will bring a lot of overhead to the CPU.
(3) Only atomic operation of one variable can be guaranteed
What CAS guarantees is the atomicity of operations performed on a variable. If operations are performed on multiple variables, CAS currently cannot directly guarantee the atomicity of operations.