Search code examples
c++multithreadingboostshared-ptr

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?


Solution

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