Boost logo

Boost :

Subject: Re: [boost] [Boost.smart_ptr] Thread Safety
From: Thomas Jordan (thomasjordan_at_[hidden])
Date: 2012-01-08 08:20:41


Message: 7
Date: Sat, 07 Jan 2012 16:49:07 -0500
From: Dave Abrahams <dave_at_[hidden]>
To: boost_at_[hidden]
Subject: Re: [boost] [Boost.smart_ptr] Thread Safety
Message-ID: <m24nw7p4j0.fsf_at_[hidden]>
Content-Type: text/plain

>on Sat Jan 07 2012, "Thomas Jordan" <thomasjordan-AT-btinternet.com> wrote:
>> Hi,
>> Is shared_array completely thread-safe, including
>> destruction/reference counting? From the code in
>> /boost/detail/sp_counted_base_pt.hpp it looks like it probably is but
>> according to
>>
>> http://www.boost.org/doc/libs/1_33_1/libs/smart_ptr/shared_ptr.htm#ThreadSafety

>I can't reach that (very ancient) page right now, but...

The documentation for this is example is the same in the latest v1.48
release.

>> // thread A
>> p3 = p2; // reads p2, writes p3
>>
>> // thread B
>> // p2 goes out of scope: undefined, the destructor is considered a "write
>> access"
>>
>> shared_ptr isn't completely thread-safe for simultaneous read and
>> write/destruct access? The same would presumbly apply to shared_array?
>> Maybe I've missed something, are there compile-time configuration
>> options to determine level of safety?

>shared_ptr<T> is almost exactly as threadsafe as T* is. In this case,
>thread A has a reference to an object on B's stack. That object is
>called p2. If thread A tries to use that object's value while the
>object is being destroyed, yeah, that's a race condition.

>The way to avoid this situation is for thread B to pass p2 to thread A
>by value, thus creating p2a, which thread A can read without concern.
>Now there's no race condition. Note: this change does /not/ cause the T
>object held by p2 to be copied.

Thanks, I think my confusion arose from my inferring that the P2 in thread A
in this example was shorthand for P2a, i.e., a copy of the actual P2 in
thread B.
Makes sense as per your interpretation.

Regards,
T.


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