1

If I want to write/read to an object from multiple threads I have to use an additional mutex for thread safety even if I use shared_pointer in C++11. Does this still apply if I use atomic_shared_pointer introduced in C++20?

Greetings

LexusA
  • 23
  • 3
  • Any help: [What is the difference between std::shared_ptr and std::experimental::atomic_shared_ptr?](https://stackoverflow.com/questions/40223599/what-is-the-difference-between-stdshared-ptr-and-stdexperimentalatomic-sha) – user4581301 Jul 06 '21 at 16:44
  • If you are modifying the object the `shared_ptr` points to, then yes. `shared_ptr` only protects itself. – NathanOliver Jul 06 '21 at 16:50

1 Answers1

7

There are three layers one might consider when thinking about the atomicity of shared_ptr.

  1. Atomicity of the reference count. That is, you have two shared_ptr objects on different threads, but they both access the same managed reference count. What happens when you copy one shared_ptr on one thread and delete a different shared_ptr that references the same reference count?

    shared_ptr provides a guarantee against race conditions in these cases. Data races on the reference count for different instances of a shared_ptr never happen.

  2. Atomicity of the shared_ptr object itself. That is, you have one shared_ptr object which is referenced by different threads. One thread may want to replace the shared_ptr's stored object or something, but someone else may be accessing it at that moment.

    C++20's atomic<shared_ptr> deals with this case. If the object is an atomic<shared_ptr>, then you can play these games through the usual atomic interface. C++11 has a number of atomic accessor functions that can achieve the same effects, so long as all code uses those accessors.

  3. Atomicity of the thing pointed to by a shared_ptr. In this case, multiple threads may be using multiple different shared_ptr objects, but all of these shared_ptr objects point to the same object. And those threads want to access the object being pointed to by them.

    This atomicity is all on you. shared_ptr's atomicity guarantees are about accesses to the pointer, not what it points to. If you need synchronized access to what is being pointed to, you will have to build that yourself.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982