Can shared_ptr.get () be called by multiple threads, and another thread is blocked and call shared_ptr.swap ()?

I would like to know if this is safe with shared_ptr. Excuse my pseudo code:

Thread 1: do lock ReadOnlyObj obj = make_shared<ReadOnlyObj>(); some_shared_ptr.swap(obj); do unlock Thread 2-N: //no lock some_shared_ptr->getterOnObj(); 

CPP link says

All member functions (including copy constructor and copy assignment) can be called by several threads in different shared_ptr instances without additional synchronization, even if these instances are copies and have ownership of the same object. If several threads execute access to the same shared_ptr without synchronization and any of these calls uses the non-constant member function shared_ptr, then data will race , redistributing shared_ptr atomic functions can be used to prevent data race.

but according to GNU docs :

Boost shared_ptr (as used by GCC) has a smart algorithm without blocking to avoid race conditions , but it depends on the processor supporting the Atom-Compare-And-Swap instruction. For other platforms, there are recessions using mutex locks. Boost (starting with version 1.35) includes several different implementations, and the preprocessor selects one based on the compiler, standard library, platform, etc. For the version of shared_ptr in libstdC ++, the compiler and library have been fixed, which makes things much easier: do we have atomic CAS or not, see the Blocking policy section below.

As far as I know, Intel x86_64 supports CAS.

So to my question:

shared_ptr :: swap is not a constant. get and → () - const. Do I need to block get / ->, given the above use case?

0
c ++ multithreading boost concurrency
source share
1 answer

I think I found the answer myself in boost docs.

 //--- Example 3 --- // thread A p = p3; // reads p3, writes p // thread B p3.reset(); // writes p3; undefined, simultaneous read/write 

What I'm trying to do is read and write at the same time, which is undefined / not safe.

+1
source share

All Articles