Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2003-02-10 14:11:11


dynalink wrote:
> Works great! How thread safe is this?

Looks as thread safe as your version, where you could end up calling
m_X.reset(new X) simultaneosly if two threads created a B at the same time.
IOW, not much. :-)

All shared_ptr/weak_ptr operations have the same thread safety level, i.e.
multiple reads are safe, writes need to be exclusive.

You'll probably need a mutex lock in A::create to make B thread-neutral.

> "Peter Dimov" <pdimov_at_[hidden]> wrote in message
> news:001301c2d12c$30c1d210$1d00a8c0_at_pdimov2...
>> dynalink wrote:
>>> I need to create a single instance of X and have it disappear when
>>> the
>>> final B pointer goes out of scope. The problem with this code is
>>> that A::m_X immediately bumps the ref count and only goes out of
>>> scope on termination.
>>>
>>> Here's a simple example:
>>>
>>> class X; // defined elsewhere; in my case wraps a classic C
>>> structure. typedef boost::smart_ptr<X> X_ptr;
>>>
>>> struct A {
>>> static X_ptr create() { if (!m_X.get()) m_X.reset(new X); return
>>> m_X; } static X_ptr m_X;
>>> };
>>>
>>> struct B {
>>> B() : m_A(A::create()){}
>>> X_ptr m_A;
>>> };
>>
>> You need to keep a weak_ptr in A.
>>
>> struct A
>> {
>> static X_ptr create()
>> {
>> if(X_ptr px = make_shared(wp_))
>> {
>> return px;
>> }
>> else
>> {
>> X_ptr px(new X);
>> wp_ = px;
>> return px;
>> }
>> }
>>
>> static weak_ptr<X> wp_;
>> };


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk