リーダー/ライターのシナリオで std::shared_ptr を使用しようとしています。1 つのスレッドが常に新しい情報を受け取り、最新のデータへのスマート ポインターを保持します。遅い計算を実行するときが来たら、すべてのデータへのスマート ポインターを取得して、一貫性のあるデータを表示していることを確認します。以下の例では、a と b を使用すると、それらが一緒に属していることがわかります。
ここでatomic_loadとatomic_storeを使用する必要があるかどうかわかりませんか? 一貫性があり有効である限り、どのバージョンの Foo を見ているかはあまり気にしません。
では、このコードを 2 つの異なるスレッドから動作させるには、スマート ポインターでアトミックを使用する必要がありますか?
ありがとう、
ポール
#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;
};
};