skip to content

In C++, which parts of std::shared_ptr are thread-safe, and what does copying one cost in a multithreaded hot path?

level: seniorimportance: must knowfreq 60%

answer

  1. the count versus the object
  2. the same instance versus copies
  3. a data race on assignment
  4. an atomic increment per copy
  5. borrow instead of copy

basics

~20 s

Count updates are safe, so separate shared_ptr copies of one object can live on different threads. Writing one shared_ptr instance while another thread reads it is a data race, the object gets no protection, and each copy costs atomic updates.

solid answer

~50 s

There are three levels. **The control block** is safe: copying and destroying *different* `shared_ptr` instances that share one object, on different threads, needs no lock — libc++ and libstdc++ update the counts with atomic operations. **One `shared_ptr` instance** is not: the standard says member functions access only the `shared_ptr` object itself for data-race purposes, so one thread assigning a global `shared_ptr` while another copies it is a data race (ThreadSanitizer reports it). Guard it with a mutex — copy under the lock, use outside it — or use `std::atomic<std::shared_ptr<T>>` (C++20; libstdc++ implements it, the pinned libc++ does not). **The pointed-to object** gets nothing; share it as `std::shared_ptr<const T>` or lock it. Each copy is an atomic increment and decrement on a shared cache line, so hot paths pass `const T&` or `const std::shared_ptr<T>&` and move instead of copying.

code

cpp · 11 lines
cpp
#include <cstdio>
#include <memory>
#include <thread>
struct Config { int max_sessions; };
std::shared_ptr<const Config> current = std::make_shared<const Config>(Config{100});
int main() {
    std::thread reader([] { for (int i = 0; i < 100000; ++i) { auto c = current; (void)c->max_sessions; } });
    std::thread writer([] { for (int i = 0; i < 1000; ++i) current = std::make_shared<const Config>(Config{i}); });
    reader.join(); writer.join();
    std::printf("%d\n", current->max_sessions);
}

go deeper

for a junior

Know that shared_ptr's counting is safe across threads but the object it points to is not protected.

for a middle

Explain the three levels - control block, instance, object - and why reassigning a shared global shared_ptr is a data race.

for a senior

Fix shared-pointer races with a mutex or atomic<shared_ptr>, publish immutable snapshots, and remove needless copies from hot paths.

for a principal

Set the rule for how shared state is published across threads, weighing immutable snapshots and lock scope against the cost of atomic counting.

## Three things, three answers "Is `std::shared_ptr` thread-safe?" has no single answer, because three different objects are involved: | object | concurrent access from several threads | |---|---| | the control block (the counts) | safe: copies and destructions of different instances need no lock | | one `shared_ptr` instance | like any object: concurrent reads are fine, a write alongside any other access is a data race | | the managed object | not protected at all; its own synchronization rules apply | ## The control block The standard's rule is that, for determining data races, `shared_ptr` and `weak_ptr` member functions access and modify only the `shared_ptr` and `weak_ptr` objects themselves, not the objects they refer to, and that changes in `use_count()` do not introduce data races. In practice that means the libraries make the count updates atomic: libc++ uses atomic increment and decrement helpers on `__shared_owners_`, and libstdc++ uses atomic read-modify-write on `_M_use_count`. libstdc++ also skips the atomic instruction while the process is single-threaded, checking `__libc_single_threaded` or `__gthread_active_p()` — an implementation optimization, not a guarantee. ## One shared_ptr instance A global `std::shared_ptr<const Config> current` that one thread reassigns while another copies it is a data race on the `shared_ptr` object: assignment rewrites both of its pointers, and a copy reads them. ThreadSanitizer reports it inside libc++'s swap of the control-block pointer, as shown on this page. Fixes: 1. **A mutex around the instance**, held only for the copy or the swap. Readers copy the pointer under the lock and use the object after unlocking; the writer swaps in a new pointer and lets the old object be destroyed after unlocking. 2. **`std::atomic<std::shared_ptr<T>>` (C++20)**, which provides `load`, `store` and `exchange` on the instance. libstdc++ implements it; the pinned libc++ does not yet (its status page lists P0718R2 as open). The older free functions `std::atomic_load(const shared_ptr<T>*)` and friends were deprecated in C++20 and removed in C++26. ## The managed object Nothing in `shared_ptr` synchronizes `*p`. Two threads calling a non-const member of the same `Session` race exactly as they would through a raw pointer. The cleanest pattern for shared configuration and other read-mostly data is **immutable snapshots**: publish `std::shared_ptr<const Config>`, never modify a published object, and replace the whole snapshot when it changes. Readers then need no lock beyond the one around the pointer itself. ## Diagnosing a race on a shared_ptr instance The symptoms are rare and ugly: a crash inside a `shared_ptr` copy constructor, a use-after-free reported far from the cause, or an object destroyed twice. They appear only under load, because the window is a handful of instructions in which the writer has replaced one of the instance's two pointers but not the other, or released the old control block while a reader was still incrementing it. The steps: 1. Run the load test under ThreadSanitizer; it reports the two conflicting accesses to the same `shared_ptr` object. 2. Find every place that writes the instance (assignment, `reset`, `swap`) and every place that reads it from another thread. 3. Put both behind the same mutex, or switch the variable to `std::atomic<std::shared_ptr<T>>` where the library provides it. ## What a copy costs Every copy of a `shared_ptr` increments the strong count and every destruction decrements it, with atomic read-modify-write instructions. When many threads copy the same `shared_ptr`, they all write the same cache line, which then moves between cores. The C++ habits that avoid it: - pass `const T&` or `T*` to functions that only use the object; - pass `const std::shared_ptr<T>&` when the callee may decide to keep a copy; - pass `std::shared_ptr<T>` by value and `std::move` into it when the callee always keeps it; - move rather than copy when handing a pointer to another thread or container. ## Common mistakes - "`shared_ptr` is thread-safe, so the object is too." - Reassigning a shared global `shared_ptr` without a lock because "the counts are atomic". - Checking `use_count() == 1` to decide an object is private to this thread; C++20 removed `shared_ptr::unique()` because that answer is unreliable with threads and weak pointers. - Passing `shared_ptr` by value everywhere, paying two atomic operations per call for no ownership change.

  • Why does passing std::shared_ptr<T> by value to every function slow a multithreaded program?
    Each by-value parameter copies the `shared_ptr` — an atomic increment of the strong count — and destroys it on return — an atomic decrement. When many threads do that on the same object, the counter's cache line bounces between cores. Pass `const T&` or `T*` to functions that only use the object, `const std::shared_ptr<T>&` when the callee may keep a copy, and move when you hand ownership over.
  • Does use_count() tell you whether it is safe to modify the object without a lock?
    No. In a multithreaded program the value can change right after you read it, because another thread can copy a `shared_ptr` or `lock()` a `weak_ptr`; C++20 removed `shared_ptr::unique()` for exactly that unreliability. Protect a shared mutable object with a mutex, or share it as `std::shared_ptr<const T>` and publish new versions instead of mutating it.

  • shared_ptr makes the pointed-to object thread-safe
  • One global shared_ptr can be reassigned while other threads copy it
  • The reference count is not thread-safe, so every copy needs a mutex
  • Copying a shared_ptr is as cheap as copying a raw pointer
  • use_count() == 1 proves no other thread can reach the object

Assumes C++20 or later for std::atomic<std::shared_ptr<T>>; C++20 also deprecated and C++26 removed the free atomic_load and atomic_store overloads for shared_ptr.