Is boost shared_ptr thread safe?

boost::shared_ptr<> offers a certain level of thread safety. The reference count is manipulated in a thread safe manner (unless you configure boost to disable threading support).

So you can copy a shared_ptr around and the ref_count is maintained correctly. What you cannot do safely in multiple threads is modify the actual shared_ptr object instance itself from multiple threads (such as calling reset() on it from multiple threads). So your usage is not safe – you’re modifying the actual shared_ptr instance in multiple threads – you’ll need to have your own protection.

In my code, shared_ptr‘s are generally locals or parameters passed by value, so there’s no issue. Getting them from one thread to another I generally use a thread-safe queue.

Of course none of this addresses the thread safety of accessing the object pointed to by the shared_ptr – that’s also up to you.

Leave a Comment