当前位置:网站首页>[multithreading] CAS mechanism analysis and application (atomic class, spin lock), solving ABA problems
[multithreading] CAS mechanism analysis and application (atomic class, spin lock), solving ABA problems
2022-07-18 06:02:00 【51CTO】
Catalog
- CAS ( Compare and swap)
- Relevant interview questions
CAS ( Compare and swap)
1、 analysis CAS
CAS: Full name Compare and swap, Literally :” Compare and exchange “, One CAS The following operations are involved :

Let's assume that the raw data in memory V, Old expectations A, New values that need to be modified B.
- Compare A And V whether equal .( Compare )
- If it's equal , take B write in V.( In exchange for )
- Whether the return operation is successful
CAS Pseudo code :
The code written below is not atomic , Actual CAS It is completed by an atomic hardware instruction . This pseudo code is just an aid to understanding
CAS workflow .

What's called here is CAS , refer to CPU Provides a separate CAS Instructions , Through this CPU Instructions, You can complete all the things that the pseudo code above needs to do .What we are discussing here CAS, In fact, this is the one discussed CPU Instructions .
This The code is obviously thread unsafehowever
If the above is “ An order ”,(CPU The above instructions are executed one by one ) At this point, the thread is safe

CAS The greatest significance , Let's write this kind of multithread safe code , It provides a new idea and direction ( It's different from a lock )
A lot of features , It can be implemented in hardware , It can also be realized by software
Just like the comparison and exchange logic just now , This is equivalent to the direct implementation of hardware , Through this instruction , Package it , Let's use it directly
2、CAS application
1. be based on CAS Can achieve “ Atomic classes ”
Java The standard library provides a set of atomic classes , More for the commonly used int, long, int array… It was packaged , Can be based on CAS The way to modify , And thread safety whole
java.util.concurrent.atomic package , The classes inside are implemented in this way
Typical is AtomicInteger class . Among them
getAndIncrement amount to i++ operation.
Running results :
In this code
There is no thread safety issue,be based on CAS Realized ++ operationThis can ensure that both Thread safety , And can compare with
synchronizedEfficient ,``synchronized` It will involve lockscompetition , Two threads have to wait for each other
CAS Thread blocking and waiting are not involved
Method :
How to implement atomic classes
How to implement atomic classes ?
Pseudo code implementation :
The illustration :

The picture means : Suppose two threads call getAndIncrement
- Both threads read value Value to oldValue in . (oldValue Is a local variable , On the stack . Each thread has its own stack )
- Threads 1 Execute first CAS operation . because oldValue and value The value of is the same , Direct to value assignment
- Threads 2 Re execution CAS operation , for the first time CAS Found that oldValue and value It's not equal , Cannot assign . Therefore, it is necessary to enter the cycle .
Reread in the loop value The value is assigned to oldValue- Threads 2 Next, execute... For the second time CAS, here oldValue and value identical , So the assignment operation is performed directly
- Threads 1 and Threads 2 Go back to their own oldValue The value of the can
2. be based on CAS Can realize spin lock
be based on CAS Achieve more flexible locks , Gain more control
Spin lock pseudocode :
The illustration :

CAS Medium ABA problem
ABA problem : Namely CAS The key to 【 Compare first , In exchange for 】
Here... And here , In fact Compare Current value and The old value Is it the same Of .
When these two values are the same , It is considered that there has been no change in the middle .
But the conclusion here has this loophole .
Current value and The old value identical , Maybe it hasn't changed in the middle .
It may also have changed , But it changed back .【 Although the final value is the same as the old value , But it did change 】
And the current decision is very hasty , As long as the values are the same, there is no change .
Such loopholes , in the majority of cases , In fact, it doesn't affect .
however ,In extreme cases, it can also cause bug.
This kind of problem , This is called ABA problem .
So-called ABA refer to :
The old value A, The current value is also A.
result
You don't know the current A, It has always been A, Or from the A Turned into B, Again from B It's back to A.
for — A typical example ,ABA Problems arise bug:
hypothesis Yes 100 deposit . Funny want to start from ATM take 50 Yuan . The ATM creates two threads , Execute concurrently -50 operation
We Expect a thread to execute -50 success , Another thread -50 Failure .
If you use CAS To complete There may be problems in this deduction process .
Normal process :
- deposit 100. Threads 1 The current deposit value obtained is 100, Expect to update to 50; Threads 2 The current deposit value obtained is 100, period
Hope to update to 50.- Threads 1 Deduction successfully executed , The deposit was changed to 50. Threads 2 Blocking waiting .
- It's the thread's turn 2 Yes , It is found that the current deposit is 50, And what I read before 100 inequality , Execution failure .
Abnormal process :
- deposit 100. Threads 1 The current deposit value obtained is 100, Expect to update to 50; Threads 2 The current deposit value obtained is 100, period
Hope to update to 50.- Threads 1 Deduction successfully executed , The deposit was changed to 50. Threads 2 Blocking waiting .
- In a thread 2 Perform before , Funny friends just give funny money 50, The account balance becomes 100 !
- It's the thread's turn 2 Yes , It is found that the current deposit is 100, And what I read before 100 identical , Perform the deduction operation again
This is the time ,
The deduction operation was performed twice! ! ! All areABA problemGhost
When you press the withdrawal operation , The machine jammed , Funny press more — Next withdrawal ~
This is equivalent to , One withdrawal operation , It was executed twice ,( Two threads , Perform the withdrawal operation concurrently ), Our expected effect should be to succeed only once !( Hope to take away 50, There is... Left in the account 50)
Suppose at the moment of withdrawal , His funny friend transferred him 50 This will trigger ABA problem

The card was transferred 50, These two coincidences lead to an existence BUG Of ABA problem ( Extreme scenario problems )
Even so bug The probability of occurrence is 0.01%, We also need to deal with !!!
How to solve ABA problem
Give the value to be modified , introduce Version number . stay CAS Compare the current value of the data with the old value , Also compare whether the version number meets the expectation
This version number
It can only grow , It can't be smaller, When changing variables , Comparison is not the comparison variable itself , But compare the version numberYou don't have to use it here “ Version number ", It can also be used. “ Time stamp "
- CAS Operation in
While reading the old value , Also read the version number- When it's really revised
- If at present The version number is the same as the read version number , Then modify the data , And put
Version number + 1.- If The current version number is higher than the read version number , The operation failed ( Think the data has been modified
in addition , You don't have to “ Version number ”, You can also use “ Time stamp ”, The date and time must go straight ahead .
So use There is no problem with timestamp .
expand :
such
be based on Version number The way To control multithreaded data, It is also a kind ofA typical implementation of optimistic locking.1、 In the database
In the database , When accessing tables through transactions concurrently , This will also involve some multithreaded operations similar to locking
2、 Version management tools (SVN)It is the collaboration of multi person development through version number .
If someone else changes , You need to pull data first , And resubmit .
Relevant interview questions
① Explain what you understand CAS Mechanism
CAS Full name Compare and swap, namely “ Compare and exchange ”.
amount to
Through the operation of an atom , Simultaneous completion “ Read memory , Comparison is equal , Modify memory ” These three steps.
Essentially, we need CPU Support of instructions.
② ABA How to solve the problem ?
Give the data to be modified
Introduce version number.stay
CAS Compare the current value of the data with the old value , Also compare whether the version number meets the expectation .If the current version number is found to be consistent with the version number read before , Just really perform the modification operation , And let the version number increase ;
If
It is found that the current version number is larger than the version number read before , It is considered that the operation failed
边栏推荐
- Beihang & Institute of Information Technology & meituan proposed lbdt, which is based on spatiotemporal interaction of language bridging to accurately segment directional video objects, with performan
- SYD_ Calculator skill 2 [manage cos]
- Where can I find the computer network speed detection
- 40+倍提升,详解 JuiceFS 元数据备份恢复性能优化之路
- 【用户文章】P4合并实践指南之实例拆解Resolve
- Pycharm使用教程:5个非常有用的技巧
- 测试开发的六大能力
- 关于 c 打印异常的问题
- i7-12700H 和 R7-6800H,这两个 CPU 差距有多大?
- 使用Excel2016的函数生成随机16、32、36位ID字符串内容
猜你喜欢

What's the use of games| Game application value research case collection
![[dynamic planning] - counting DP](/img/28/254790a65bd4e4803815147fc9b7ef.png)
[dynamic planning] - counting DP

2022年高处安装、维护、拆除考题模拟考试平台操作

How can win11 maximize the software interface by default? Win11 opens the software interface by default to maximize

【多线程】 CAS 机制解析及应用( 原子类 . 自旋锁 )、解决 ABA 问题

What if there is no sound when playing lol after reinstalling the system win11?

SQL每日一练(牛客新题库)——第2天: 条件查询

授人以渔-在 SAP MM 物料显示界面上看到一个字段,如何查找哪张数据库表的哪个字段进行的存储的试读版

工程监测振弦无线采集仪外接数字传感器接入逻辑与数据发送

Teach people to fish - see a field on the sap mm material display interface, how to find which field of which database table to store the trial version
随机推荐
Sword finger offer punch stack queue heap
Apache apisik meetup Nanjing station! See you at 7.30!
Interview question set
网络安全网格概念以及特点简单普及
@Difference between controller and @restcontroller
Win11如何默认打开软件界面最大化?Win11默认打开软件界面最大化
【多线程】 CAS 机制解析及应用( 原子类 . 自旋锁 )、解决 ABA 问题
用对工具,CI事半功倍
Six capabilities of test and development
[comprehensive pen test] difficulty 2/5, recursive application, prefix and optimization
七 异常处理
IM即时通讯软件开发之扫码登录功能
Single view reconstruction -- deduction of shadow vanishing points, shadow vanishing lines, camera internal parameters and plane normal vectors
O & M - mélange de compétences
ComboBoxEdit设置选项值(单选 多选)
深度学习基础:8.卷积与池化
使用Excel2016的函数生成随机16、32、36位ID字符串内容
差距大?不同学历考生考研的要求和条件
Win11如何设置多任务窗口?Win11设置多任务窗口的方法
i7-12700H 和 R7-6800H,这两个 CPU 差距有多大?
