c++11:std::atomic<T>::compare_exchange_weak, std::atomic<T>::compare_exchange_strong
头文件:<atomic>函数声明:boolcompare_exchange_weak(T&expected, T desired,std::memory_ordersuccess,std::memory_order failure)noexcept;原子地比较*this和expected的值,而若它们逐位相等,则以d...
头文件:<atomic>
函数声明:
bool compare_exchange_weak( T& expected, T desired, std::memory_order success, std::memory_order failure ) noexcept; | 原子地比较 否则,将
|
bool compare_exchange_weak( T& expected, T desired, std::memory_order success, std::memory_order failure ) volatile noexcept; | |
bool compare_exchange_weak( T& expected, T desired, std::memory_order order = std::memory_order_seq_cst ) noexcept; | |
bool compare_exchange_weak( T& expected, T desired, std::memory_order order = std::memory_order_seq_cst ) volatile noexcept; | |
bool compare_exchange_strong( T& expected, T desired, std::memory_order success, std::memory_order failure ) noexcept; | |
bool compare_exchange_strong( T& expected, T desired, std::memory_order success, std::memory_order failure ) volatile noexcept; | |
bool compare_exchange_strong( T& expected, T desired, std::memory_order order = std::memory_order_seq_cst) noexcept; | |
bool compare_exchange_strong( T& expected, T desired, std::memory_order order = std::memory_order_seq_cst ) volatile noexcept; |
#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 被修改为 ai的值,返回值为false
exchanged= ai.compare_exchange_strong( tst_val, new_val );
valsout();
// tst_val == ai ==> ai 被修改为 new_val的值,返回值为true
exchanged= ai.compare_exchange_strong( tst_val, new_val );
valsout();
}
运行结果:
更多推荐
所有评论(0)