Copy-on-write with shared_ptr for multithreading

In the absence of multithreading, the implementation of copy-on-write for shared_ptr(either from boost or tr1) using unique()is simple. What changes need to be made with multithreading? The reference count is atomic, so I assume that I can create, copy-build, read and destroy instances shared_ptrwithout additional problems. How about updating them in general, and especially when implementing copy-on-write? Do you need locks? Or use boost::atomic_store (why is this not documented)? Or wait for the fully atomic version shared_ptr(not an option)?

Edit:
sfossen, thanks for your reply. Therefore, I conclude that if I change the object with a pointer to the object only after disconnecting it through COW, so that it only owns the current thread, it does not require blocking and the COW implementation looks the same as single-threaded when using shared_ptr with atomic reflexes.

+3
source share
2 answers

With COW, you only need to block when copying objects that may be in the middle of a change.

So, if the COW of an object is an object that is configured before threads and never changes, no lock is required.

, , , , .

, .

:

, .

boost, , , /.

shared_ptr.hpp

template<class T> shared_ptr<T> atomic_exchange( shared_ptr<T> * p, shared_ptr<T> r )
{
    boost::detail::spinlock & sp = boost::detail::spinlock_pool<2>::spinlock_for( p );

    sp.lock();
    p->swap( r );
    sp.unlock();

    return r; // return std::move( r )
}

RWLocks

+6

shared_ptr - , , . shared_ptr, , shared_ptr shared_ptr, .

, , , , shared_ptr , , ++ 0x. shared_ptr, , , shared_ptr .

0

Source: https://habr.com/ru/post/1704305/


All Articles