当前位置:网站首页>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,
边栏推荐
- 遗留系统的自动化策略
- 学习DAVID数据库(1)
- C primer plus学习笔记 —— 8、结构体
- Modbus on AT32 MCU
- 分布式系统架构需要解决的问题
- Unity3D Button 鼠标悬浮进入与鼠标悬浮退出按钮事件
- [C language foundation] Solve C language error: expected ';', ',' or ')' before '&' token
- 5. SAP ABAP OData 服务如何支持 $filter (过滤)操作
- Clustering index, and what is the difference between a clustering index
- 10 权限介绍
猜你喜欢
The simulation application of common mode inductance is here, full of dry goods for everyone
Intel's software and hardware optimization empowers Neusoft to accelerate the arrival of the era of smart medical care
Office automation case: how to automatically generate period data?
【编译原理】词法分析程序设计原理与实现
Mysql 45讲学习笔记(二十四)MYSQL主从一致
一份高质量的测试用例如何养成?
C# remote debugging
【C语言】求两个整数m和n的最大公因数和最小公倍数之和一般方法,经典解法
10 权限介绍
The use of font compression artifact font-spider
随机推荐
SQL注入 Less54(限制次数的SQL注入+union注入)
工程(五)——小目标检测tph-yolov5
Chapter 9 SVM实践
测试中的误报和漏报同样的值得反复修正
TCP详解(二)
跨专业考研难度大?“上岸”成功率低?这份实用攻略请收下!
【异常】The field file exceeds its maximum permitted size of 1048576 bytes.
Moxa NPort device flaw could expose critical infrastructure to devastating attack
加密公司向盗窃的黑客提供报价:保留一点,把剩下的归还
MultipartFile file upload
8、统一处理异常(控制器通知@ControllerAdvice全局配置类、@ExceptionHandler统一处理异常)
SQL injection Less54 (limited number of SQL injection + union injection)
Pythagorean tuple od js
软件积累 -- 截图软件ScreenToGif
编译Hudi
字体压缩神器font-spider的使用
15. Website Statistics
【C语言】三子棋(经典解法+一览图)
图解lower_bound&upper_bound
接口测试关键技术