Multithreading atomicity: CAS and ABA issues

CAS (Compare And Swap (Compare And Exchange) comparison and exchange): the update of a value by multiple threads can be guaranteed without a lock

       Normally, in order to ensure safety, it is necessary to lock when a thread accesses a value, but in order to ensure efficiency, the CAS is not locked.

       Listed as:

       Now there is a value of 0, read this value and store it in E, then: E=0. Then perform an increment operation on E, and set the calculation result as V. After E++, set a new value to N (ie: N=E++), then check E. If E is still 0, it means that no other threads modify E, and then update E to the new value V. If E! =0, it means that other threads have modified E. At this time, let E be equal to the value modified by other threads, and then follow the previous steps again, that is: current E=E'=2 (assuming E is modified to 2 by other threads), E is incremented, E++, there is a calculation result The value V, V=3, and then see if E is still 2. If E=2, it means that no other thread modifies E. At this time, modify E to the new value V, E=3;

At this time, some friends will have doubts. If after the E operation obtains the new value N, check the value of E and find that E has not changed (originally E=0, now E=0), and then you are ready to assign V During the period of E, a thread changes the value of E, and then another thread changes the value of E back to the original value (E=0, thread 1 changes E to 3, thread 2 changes E again Returned to 0), the E we saw at this time is actually not the original E anymore. (It's like your girlfriend broke up with you. During your breakup, she found another boyfriend, and then they broke up. You reconcile again. At this time, your girlfriend is no longer the original girlfriend!! !!!)

So here is the ABA question:

ABA problem: other threads modify a value multiple times, and the final value is the same as the original value

 

 

Guess you like

Origin blog.csdn.net/qq_44624536/article/details/114598203