我希望在读取器/写入器场景中使用 std::shared_ptr 。一个线程不断接收新信息并保持一个指向最新数据的智能指针。当需要运行我的慢速计算时,我将智能指针指向所有数据,以确保我正在查看一致的数据。在下面的示例中,当我使用 a 和 b 时,我知道它们属于一起。
我不确定我是否应该在这里使用 atomic_load 和 atomic_store ?只要它是一致且有效的,我并不关心我正在查看哪个版本的 Foo。
那么我应该在我的智能指针上使用 atomic 以便让这段代码在两个不同的线程中工作吗?
谢谢,
保罗
#include <iostream>
#include <memory>
class Foo{
public:
int a;
int b;
};
class MyClass{
public:
std::shared_ptr <Foo> lastValue;
void realTimeUpdate (Foo* latest) { //takes ownership of Foo
lastValue=std::shared_ptr <Foo> (latest); //Is this OK to do without using std::atomic_?
};
void doSlowCalcFromAnotherThread () {
//take a reference to all input data
std::shared_ptr <Foo> stableValue=lastValue; //Is this OK to do without using std::atomic_
//display a and b guaranteed that they come from the same message
std::cout<<"a: "<<stableValue->a<<std::endl;
std::cout<<"b: "<<stableValue->b<<std::endl;
};
};