Raise shared pointer: concurrent read access across multiple threads

I have thread A that allocates memory and assigns it to a shared pointer. Then this thread generates 3 other threads X, Y and Z and passes a copy of the common pointer to each. When X, Y and Z go beyond, memory is freed. But is there a chance that 2 threads X, Y will leave the scope at the same time, and there is a race condition on the link counter, instead of decrementing it by 2, it only decreases once. So, now the reference count is reduced to 0, so a memory leak occurs. Note that X, Y, and Z only read memory. Do not write or restore the shared pointer. In short, could there be a race condition on the link counter and could this lead to memory leaks?

+6
c ++ multithreading boost shared-ptr
source share
5 answers

Some others have already provided links to documentation explaining that it is safe.

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

+2
source share

boost::shared_ptr uses locks (or block atomic access) to ensure that reference counts are updated atomically (even if this is not clear from the docs page). You can configure the use of locks if you write single-threaded code by defining the macro BOOST_SP_DISABLE_THREADS .

Please note that the documentation examples at http://www.boost.org/doc/libs/1_42_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety , which discuss problems with several records from different threads, discuss those threads acting on that but shared_ptr ( shared_ptr objects can be global in the examples), and not different shared_ptr copies that point to the same object, which is a common use case for shared_ptr . The example you ask in the question (acting on copies pointing to a shared object) is thread safe.

+12
source share

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

Different instances of shared_ptr can be "written to" (accessed by modifiable operations such as operator = or reset) simultaneously by multiple threads (even if these instances are copies and share the same reference counter below).

+6
source share

The documentation says:

Different instances of shared_ptr can be "written to" (accessed by mutable operations such as operator = or reset) simultaneously by multiple threads (even if these instances are copies and share the same reference counter below).

So, if none of the threads accesses pointer objects of other threads, this should be fine. Please check out the examples in the documentation and see which one matters in your case.

+1
source share

It would be best to upgrade to TR1 or C ++ 0x shared_ptr, unlike the Boost variety. I believe that he standardized that they MUST be thread safe.

-2
source share

All Articles