1、声明头文件
#include <atomic>
原子操作: 对一个变量的访问操作,原来会分为好几个指令,由于多线程程序中,可能会存在数据竞争,可能导致对变量的操作不是原子性,那么从编译实现角度,将原本几个指令的操作变成一个指令来执行,可以在无锁情况下实现原子操作,从而避免数据竞争。
std::atomic::atomic
default (1)
atomic() noexcept = default;
initialization (2)
constexpr atomic (T val) noexcept;
copy [deleted] (3)
atomic (const atomic&) = delete;
Construct atomic
Constructs an atomic object:
(1) default constructor
Leaves the atomic object in an uninitialized state.
An uninitialized atomic object may later be initialized by calling atomic_init.
(2) initialization constructor
Initializes the object with val.
(3) copy construction
Deleted (atomic objects cannot be copied/moved).
注意: atomic不可拷贝和移动
2、函数
atomic::store
Modify contained value (public member function ) 原子地修改容器中的值
atomic::load
Read contained value (public member function ) 原子地读取容器中的值
std::atomic::compare_exchange_strong
bool compare_exchange_weak( T& expected, T desired,std::memory_order success,std::memory_order failure );
bool compare_exchange_weak( T& expected, T desired,std::memory_order success,std::memory_order failure ) volatile;
bool compare_exchange_weak( T& expected, T desired,std::memory_order order = std::memory_order_seq_cst );
bool compare_exchange_weak( T& expected, T desired,std::memory_order order = std::memory_order_seq_cst ) volatile;
bool compare_exchange_strong( T& expected, T desired,std::memory_order success,std::memory_order failure );
bool compare_exchange_strong( T& expected, T desired,std::memory_order success,std::memory_order failure ) volatile;
bool compare_exchange_strong( T& expected, T desired,std::memory_order order = std::memory_order_seq_cst );
bool compare_exchange_strong( T& expected, T desired,std::memory_order order =std::memory_order_seq_cst ) volatile;
expected-reference to the value expected to be found in the atomic object
desired-the value to store in the atomic object if it is as expected
success-the memory synchronization ordering for the read-modify-write operation if the comparison succeeds. All values are permitted.
failure-the memory synchronization ordering for the load operation if the comparison fails. Cannot be std::memory_order_release or std::memory_order_acq_rel and cannot specify stronger ordering than success (until C++17)
order-the memory synchronization ordering for both operations
返回值:true如果成功地更改了基础原子值,false否则。
3、使用
std::atomic<int> ai;
ai.store(3);
exchanged= ai.compare_exchange_strong( tst_val, new_val );
exchanged= ai.compare_exchange_strong( tst_val, new_val );
- 当ai = 3时,ai不等于 tst_val, 将tst_val 的值设为3,返回false。
- 当ai= 3时,ai 等于tst_val, 将tst_val 的值设为new_val, 即将5赋值给ai,返回true。
|