Is boost shared_ptr thread safe?

后端 未结 5 598
灰色年华
灰色年华 2020-12-01 03:22

I have a question about boost::shared_ptr.

There are lots of thread.

using namespace boost;

class CResource
{
  // xxxxxx
}

c         


        
5条回答
  •  粉色の甜心
    2020-12-01 04:10

    Well, tr1::shared_ptr (which is based on boost) documentation tells a different story, which implies that resource management is thread safe, whereas access to the resource is not.

    "...

    Thread Safety

    C++0x-only features are: rvalue-ref/move support, allocator support, aliasing constructor, make_shared & allocate_shared. Additionally, the constructors taking auto_ptr parameters are deprecated in C++0x mode.

    The Thread Safety section of the Boost shared_ptr documentation says "shared_ptr objects offer the same level of thread safety as built-in types." The implementation must ensure that concurrent updates to separate shared_ptr instances are correct even when those instances share a reference count e.g.

    shared_ptr a(new A); shared_ptr b(a);

    // Thread 1 // Thread 2

    a.reset(); b.reset();

    The dynamically-allocated object must be destroyed by exactly one of the threads. Weak references make things even more interesting. The shared state used to implement shared_ptr must be transparent to the user and invariants must be preserved at all times. The key pieces of shared state are the strong and weak reference counts. Updates to these need to be atomic and visible to all threads to ensure correct cleanup of the managed resource (which is, after all, shared_ptr's job!) On multi-processor systems memory synchronisation may be needed so that reference-count updates and the destruction of the managed resource are race-free.

    ..."

    see http://gcc.gnu.org/onlinedocs/libstdc++/manual/memory.html#std.util.memory.shared_ptr

提交回复
热议问题