Is it safe to copy and reset shared_ptr at the same time?
Namely consider the following code
// Main thread (before creating any other threads)
shared_ptr<A> a(new A(1));
// Thread 1
shared_ptr<A> a_copy = a;
// Thread 2
a.reset(new(A(2));
where thread 1 and 2 run in parallel. Can I be sure, that a_copy
will store pointer either to the older A(1)
or to the newer A(2)
shared object?
A std::shared_ptr consists of a control block and its resource. The control block is thread-safe, but access to the resource is not. This means modifying the reference counter is an atomic operation and you have the guarantee that the resource is deleted exactly once.
No there no standard atomic functions for std::unique_ptr .
std::shared_ptr is not thread safe. A shared pointer is a pair of two pointers, one to the object and one to a control block (holding the ref counter, links to weak pointers ...).
std::shared_ptr:All operations, that do not change the reference count, are as lock-free as the corresponding operations on a raw pointer. That includes the operations dereferencing and move construction. std::move is lock-free, because it is only a cast to an rvalue-reference.
From cppreference:
All member functions (including copy constructor and copy assignment) can be called by multiple threads on different instances of
shared_ptr
without additional synchronization even if these instances are copies and share ownership of the same object.
So, the answer is no — these operations are not thread-safe because both the copy and the reset are applied to the same instance, a
. The result is a data race, which leads to undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With