问题描述
我无法理解和编写与以下针对用户定义的数据类型的原子库功能相关的代码:
std :: atomic :: compare_exchange_weak, std :: atomic :: compare_exchange_strong
bool compare_exchange_weak( T& expected,T desired,std::memory_order success,std::memory_order failure );
bool compare_exchange_strong( T& expected,std::memory_order failure );
因此,如果我在普通班级以下,如何在该普通班级上使用compare_exchange_weak / compare_exchange_strong原子库方法?
class A
{
public:
void Show()
{
std::cout << "Called\n";
}
};
我不确定我们应该在用户定义的数据类型(例如A类)的方法中设置什么期望值/期望值?
解决方法
您的课程没有数据,因此不需要使用std::atomic<A>
。如果您想知道如何将std::atomic
与UDT一起使用,可以添加成员数据,然后使用以下代码
#include <iostream>
#include <atomic>
class A
{
public:
int a;
void Show()
{
std::cout << a << "\n";
}
};
int main( ) {
A a1{1};
A a2{2};
std::atomic<A> atomicA{a1};
atomicA.load().Show();//the original atomicA
atomicA.compare_exchange_strong(a2,A{2});// this makes no change
atomicA.load().Show();
atomicA.compare_exchange_strong(a1,A{2});//this changes atomicA
atomicA.load().Show();
}
请注意,并非所有UDT都能获得真实的原子行为(可以使用锁来实现)。要确保您的原子具有真实的原子行为,可以使用atomicA.is_lock_free()
。