1

I am trying to set the value of a shared_ptr in an atomic way:

shared_ptr<Base> a = std::make_shared<Derived>();
....
shared_ptr<Base> b;
std::atomic_store(&b,a); // Error here

I got the error message "'std::shared_ptr< Base >' is not derived from 'volatile std::atomic<_ITp>'"

How to fix this? Thanks.

Maluvel
  • 425
  • 1
  • 6
  • 13
  • 1
    Basically the way to do this in a thread safe way is to use a mutex. You may want to wrap the shared pointer and mutex in a class to guarantee that nobody can set the shared pointer without grabbing the mutex. – Nir Friedman May 30 '17 at 18:53
  • 1
    @NirFriedman mutex doesn't guarantee that the access is volatile, so not good enough. – Maluvel Jun 01 '17 at 10:58
  • 1
    Uhm what? Volatile probably doesn't mean what you think it does, you should read up on it. https://stackoverflow.com/questions/36496692/should-stdatomic-be-volatile. – Nir Friedman Jun 01 '17 at 13:47
  • 1
    Thanks for the link. Still what I want to achieve is "inter-thread synchronization", meaning var value should be seen the same among threads. Does shared_ptr have this feature? – Maluvel Jun 01 '17 at 15:01
  • The quotes are not necessary. Mutexes are perhaps the simplest way to achieve inter-thread communication. Wrapping a variable in a mutex would mean that only one thread could read or write the mutex at a time. Each thread is therefore guaranteed to always see a consistent value of the variable. It does not matter whether that varaible is a shared_ptr or something else. – Nir Friedman Jun 01 '17 at 16:13
  • 1
    @NirFriedman pls correct me if I am wrong. As a long time user of mutex, I understand that it only helps to lock the Content inside its guarded block (its impl is self-explanatory). However, it does NOT guarantee that changes to the content is instantly seen by other threads (volatile feature) – Maluvel Jun 02 '17 at 07:54
  • I do not know what you mean by "instantly". That is not what volatile does. Volatile basically just says that the program cannot elide any reads or writes for that variable. With a mutex, within the lock things can be elided but that doesn't matter because only one thread is there. mutex's are required to sync so no reads/writes can be elided across the mutex boundary. tl; dr mutexes are fine for this and I still think there is some kind of lack of clarity about what you want. – Nir Friedman Jun 02 '17 at 13:26

1 Answers1

3

There is a specialization of atomic_store for std::shared_ptr, see

http://en.cppreference.com/w/cpp/memory/shared_ptr/atomic

And by modern compilers (say, GCC 5) the code you provide is compiled just fine. So I suppose you compiler is not fully support C++11 (just like GCC 4.x, that lacks the specialization).