Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost Shared Pointer: Simultaneous Read Access Across Multiple Threads

I have a thread A which allocates memory and assigns it to a shared pointer. Then this thread spawns 3 other threads X, Y and Z and passes a copy of the shared pointer to each. When X, Y and Z go out of scope, the memory is freed. But is there a possibility that 2 threads X, Y go out of scope at the exact same point in time and there is a race condition on reference count so instead of decrementing it by 2, it only gets decremented once. So, now the reference count newer drops to 0, so there is a memory leak. Note that, X, Y and Z are only reading the memory. Not writing or resetting the shared pointer. To cut a long story short, can there be a race condition on the reference count and can that lead to memory leaks?

like image 238
Nikhil Avatar asked Apr 21 '10 22:04

Nikhil


3 Answers

boost::shared_ptr uses locks (or lock-free atomic access) to ensure that reference counts are updated atomically (even if this isn't clear from the docs page). You can configure away the use of the locks if you're writing single threaded code by defining the macro BOOST_SP_DISABLE_THREADS.

Note that the documentation examples in http://www.boost.org/doc/libs/1_42_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety that discuss problems with multiple writes from different threads is discussing those threads acting on the same shared_ptr instances (the shared_ptr objects might be globals in the examples), not different shared_ptr copies that point to the same object, which is the usual use case for shared_ptr's. The example you give in the question (acting on copies that point to the shared object) is thread-safe.

like image 111
Michael Burr Avatar answered Sep 28 '22 08:09

Michael Burr


No, according to the documentation, these problems cannot occur:

Different shared_ptr instances can be "written to" (accessed using mutable operations such as operator= or reset) simultaneosly by multiple threads (even when these instances are copies, and share the same reference count underneath.)

like image 20
sth Avatar answered Sep 28 '22 09:09

sth


Several others have already provided links to the documentation explaining that this is safe.

For absolutely irrefutable proof, see how Boost Smartptr actually implements its own mutexes from scratch in boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp (or your platform's corresponding file).

like image 26
Potatoswatter Avatar answered Sep 28 '22 08:09

Potatoswatter