Do I need to use std :: atomic_ when using one reader and one write stream

I want to use std :: shared_ptr in a read / write script. One thread constantly receives new information and stores a smart pointer to the latest data. When the time comes to start my slow calculation, I take a smart pointer to all the data to make sure I'm looking for consistent data. In the example below, when I use a and then b, I know that they belong to each other.

I'm not sure if atomic_source and atomic_string should be used here? I don’t care which version of Foo I am considering as long as it is consistent and valid.

So, should atoms be used here on their smart pointers so that this code works from two different threads?

Thank,

Floor

#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;
  };
};
+4
3
  • shared_ptr:: operator = .
  • shared_ptr TriviallyCopyable, std:: atomic.

, - , . std:: mutex.

+2

, std::atomic_load() std::atomic_store(), memory std::shared_ptr. . ( , , ++ 11, .)

+2

, - . , std::shared_ptr<>::operator= , , undefined,

+1
source

All Articles