【C++编程】函数compare_exchange_strong
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;
用法: 原子的比较 *this
和 expect的值
,若它们逐位相等,则以 desired
替换前者(进行读修改写操作)。否则,将 *this
中的实际值加载进 expected
(进行加载操作)。
#include <atomic>
#include <iostream>
std::atomic<int> ai;
int tst_val= 4;
int new_val= 5;
bool exchanged= false;
void valsout()
{
std::cout << "ai= " << ai
<< " tst_val= " << tst_val
<< " new_val= " << new_val
<< " exchanged= " << std::boolalpha << exchanged
<< "\n";
}
int main()
{
ai= 3;
valsout();
// tst_val != ai ==> tst_val is modified
exchanged= ai.compare_exchange_strong( tst_val, new_val );
valsout();
// tst_val == ai ==> ai is modified
exchanged= ai.compare_exchange_strong( tst_val, new_val );
valsout();
}
分析:
1. 当ai = 3时,ai不等于 tst_val, 将tst_val 的值设为3,返回false。
2. 当ai= 3时,ai 等于tst_val, 将tst_val 的值设为new_val, 即将5赋值给ai,返回true。
参考资料
1 . std::atomic<T>::compare_exchange_weak, std::atomic<T>::compare_exchange_strong的用法