CAS Implementation Principle
CAS stands for CompareAndSwap, which means CompareAndSwap. It is lock-free and the implementation is classic optimistic locking.
The CAS operation is simple and contains three operands: the memory address V, the expected old value A, and the new value B. First, compare whether the value at memory address V is equal to the original expected value A. If so, update the value at memory address V to the new value B. When used in conjunction with a loop, if the CAS operation fails, the loop is executed or some termination is reached. This operation is also known as a spinlock implementation when used in a loop.
Problems with CAS
1. ABA problems
For example, when A thread operates, it first updates the value A at memory address V to value B, and then updates the value B to value A. Finally, CAS judges that there is no change at the memory address V and considers that the operation update failed, but in essence, it has been updated. This is the classic ABA problem.
Solutions:
- Add time stamp:
- Plus version number:
2. High cycle overhead
CAS is also an optimistic lock. If there are many threads, intense resource preemption, and low hit ratio, the continuous loop will consume resources continuously. In implementation, you can set the maximum number of cycles, to reach the maximum number of cycles has not occupied the resource will automatically give up, to avoid infinite cycles.
3. Only one shared variable operation can be guaranteed
CAS can operate on a maximum of one shared variable.