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
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
There are three layers one might consider when thinking about the atomicity of shared_ptr
.
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.
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.
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.