About thread-safety of weak_ptr

I know I’m late, but this comes up when searching for “weak_ptr thread”, and Casey’s answer just isn’t the whole truth. Both shared_ptr and weak_ptr can be used from threads without further synchronization.

For shared_ptr, there’s a lot of documentation (e.g. on cppreference.com or on stackoverflow). You can safely access shared_ptr‘s that point to the same object from different threads. You just can’t bang on the same pointer from two threads. In other words:

// Using p and p_copy from two threads is fine.
// Using p from two threads or p and p_ref from two threads is illegal.
std::shared_ptr<A> p = std::make_shared<A>();
std::shared_ptr<A> &p_ref = p;
std::shared_ptr<A> p_copy = p;

To solve that problem in your code, pass g_s as parameter (by value)* to f1().

For weak pointers, the safety guarantee is hidden in the documentation for weak_ptr::lock:

Effectively returns expired() ? shared_ptr<T>() : shared_ptr<T>(*this), executed atomically.

You can use weak_ptr::lock() to get a shared_ptr from other threads without further synchronization. This is also confirmed here for Boost and in this SO answer by Chris Jester-Young.

Again, you have to make sure not to modify the same weak_ptr from one thread while accessing it from another, so pass g_w into f3() by value as well.

Leave a Comment