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;
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
(进行加载操作)。
1 #include <atomic> 2 #include <iostream> 3 4 std::atomic<int> ai; 5 6 int tst_val= 4; 7 int new_val= 5; 8 bool exchanged= false; 9 10 void valsout() 11 { 12 std::cout << "ai= " << ai 13 << " tst_val= " << tst_val 14 << " new_val= " << new_val 15 << " exchanged= " << std::boolalpha << exchanged 16 << " "; 17 } 18 19 int main() 20 { 21 ai= 3; 22 valsout(); 23 24 // tst_val != ai ==> tst_val is modified 25 exchanged= ai.compare_exchange_strong( tst_val, new_val ); 26 valsout(); 27 28 // tst_val == ai ==> ai is modified 29 exchanged= ai.compare_exchange_strong( tst_val, new_val ); 30 valsout(); 31 }
分析:
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的用法