Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are operations with the internal pointer of shared_ptr atomic?

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?

like image 622
Mihran Hovsepyan Avatar asked Aug 10 '15 07:08

Mihran Hovsepyan


People also ask

Is shared_ptr Atomic?

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.

Is Unique_ptr Atomic?

No there no standard atomic functions for std::unique_ptr .

Is shared_ptr thread safe?

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 ...).

Is shared_ptr lock free?

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.


1 Answers

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.

like image 131
Potatoswatter Avatar answered Oct 09 '22 05:10

Potatoswatter