当前位置:网站首页>Atomic operation CAS
Atomic operation CAS
2022-07-31 03:03:00 【JACKSONMHLN】
Reference:
https://zhuanlan.zhihu.com/p/400817892
https://www.bilibili.com/read/cv10686883/
https://blog.csdn.net/www_dong/article/details/119920236
https://blog.csdn.net/niu91/article/details/116308436
https://blog.csdn.net/CringKong/article/details/79966161
1, atomic operation
Atomic operation, an operation that will not be interrupted by the thread scheduling mechanism.Once the operation starts, it runs to the end without any context switches in between.
Typical atomic operations are (atomic operations require hardware support)
Load / Store: read and write memory
Test and Set: For bool variables, if true, return true, if false, set the variable to true and return false.
Clear: Set the bool variable to false.
Exchange: Sets the value at the specified location to the incoming value and returns its old value.
Compare and Swap: Compares the value at the specified position with the expected value, assigning the new value if they are equal, and setting the expected value to itself if they are not equal.Returns whether the setting is successful.
Fetch And series of addition, subtraction, multiplication and division: perform addition, subtraction, multiplication and division on the value at the specified position using the incoming parameters, and return the old value.
2. Race Conditon
int i = 0;i++;mov eax,dword ptr [i] // load i into the eax registeradd eax,1 // add one to the value in eaxmov dword ptr [i],eax // assign the value in eax to the address of i There are three steps at the assembly level: read-modify-write.Thread 1 has not written to the memory after modification. Thread 2 gets the CPU and starts to execute. The modified value will be the value that thread 1 has not written to the memory. There is a thread safety problem.
4, thread safety
There are usually the following ways to solve thread safety:
1. Use atomic operations.
2. Lock: pessimistic lock or optimistic lock (no lock)
1, atomic_int num; num++;
In msvc, the atomic_int type proposed by C++11, in the num++ operation, the bottom layer calls the atomic increment function _InterlockedIncrement provided by windows.
2. Pessimistic lock
mutex is a use of pessimistic locking.Assuming concurrency violations will occur, block any operations that might violate data integrity.
3, optimistic lock
Assuming that there will be no concurrency conflicts, each time an operation is completed without locking but assuming there is no conflict, and only checks whether data integrity is violated when the operation is submitted.
CAS (Compare And Swap) operation is a atomic instruction of the CPU, so there is no thread safety problem.
CAS(addr,old,new)Explanation: Only compare what addr stores with old, and if it is equal to old, assign new to addr.
C++ can be implemented as follows:
bool compare_and_swap(int* pAddr, int nExpected, int nNew) {if (*pAddr == nExpected) {*pAddr = nNew;return true;}elsereturn false;}The underlying implementation of different compilers is different, but the algorithm idea is the same.
GCC's CAS, the atomic operation of CAS is supported in GCC4.1+.
1) bool __sync_bool_compare_and_swap (type *ptr, type oldval, type newval, ...)2) type __sync_val_compare_and_swap (type *ptr, type oldval, type newval, ...)CAS in C++11, the atomic class functions in STL in C++11 allow you to cross-platform.
template< class T > bool atomic_compare_exchange_weak( std::atomic* obj,T* expected, T desired );template< class T > bool atomic_compare_exchange_weak( volatile std::atomic* obj,T* expected, T desired );CAS for Windows
InterlockedCompareExchange ( __inoutLONGvolatile *Target,__inLONGExchange,__inLONGComperand);Problems with CAS: ABA.
Solution: Double CAS, that is, you can add a version number.
Things like status registers, I/O operations mapped to memory addresses, and variables that involve hardware operations need to be volatile because every operation on them has its meaningstrong>,
In the case of concurrency, multi-threading and multi-tasking should use atomic weight and memory order, or directly add mutualExclusive locks to ensure atomicity and ordering of shared area operations.
So in fact, volatile and atomic are used in different scenarios, and they can even be used superimposed.For example:
volatile std::atomic value; This formula means that all operations on value are atomic,
边栏推荐
- The distance value between two arrays of LeetCode simple questions
- 6. Display comments and replies
- 分布式系统架构需要解决的问题
- Ambiguous method call.both
- 6、显示评论和回复
- 12 Disk related commands
- 8. Unified exception handling (controller notifies @ControllerAdvice global configuration class, @ExceptionHandler handles exceptions uniformly)
- 【Android】Room —— SQLite的替代品
- Clustering index, and what is the difference between a clustering index
- Thesis framework of the opening report
猜你喜欢

关于 mysql8.0数据库中主键位id,使用replace插入id为0时,实际id插入后自增导致数据重复插入 的解决方法

共模电感的仿真应用来了,满满的干货送给大家

刚出道“一战成名”,安全、舒适一个不落
![Installation of mysql5.7.37 under CentOS7 [perfect solution]](/img/ef/a89d8bfd09377dc30034bad99dfd07.png)
Installation of mysql5.7.37 under CentOS7 [perfect solution]

6. Display comments and replies

12 磁盘相关命令

CorelDRAW2022 streamlined Asia Pacific new features in detail

TCP详解(三)
![[Android] Room - Alternative to SQLite](/img/52/0bc1c0a3173da6d39224ad8440a462.png)
[Android] Room - Alternative to SQLite

Getting Started with CefSharp - winform
随机推荐
CefSharp入门-winform
递归查询单表-单表树结构-(自用)
解析小结—自用
TCP/IP four-layer model
TCP详解(三)
JS function this context runtime syntax parentheses array IIFE timer delay self.backup context call apply
【编译原理】递归下降语法分析设计原理与实现
SQL injection Less47 (error injection) and Less49 (time blind injection)
10 Permission introduction
Addition and Subtraction of Scores in LeetCode Medium Questions
10. Redis implements likes (Set) and obtains the total number of likes
4、敏感词过滤(前缀树)
CentOS7下mysql5.7.37的安装【完美方案】
The difference between link and @import
[Android] Room - Alternative to SQLite
点云DBSCAN聚类(MATLAB,非内置函数)
分布式系统架构需要解决的问题
2022 Nioke Multi-School League Game 4 Solution
Unity3D Button mouse hover enter and mouse hover exit button events
10 权限介绍