Boost logo

Boost Users :

Subject: Re: [Boost-users] Thread Safety of shared_ptr
From: Cory Nelson (phrosty_at_[hidden])
Date: 2011-05-03 18:17:37


On Tue, May 3, 2011 at 12:59 PM, Ovanes Markarian
<om_boost_at_[hidden]> wrote:
>
>
> On Tue, May 3, 2011 at 2:18 PM, Peter Dimov <pdimov_at_[hidden]> wrote:
>>
>> Kevin Frey wrote:
>>
>>> 2.       One thread A creating another shared_ptr to the shared object,
>>> attempting to increment the reference count.
>>>
>>> 3.       Another thread B simultaneously destroying a *different*
>>> shared_ptr which is connected to the same underlying shared object,
>>> decrementing the reference count.
>>
>> This is OK. Manipulating different shared_ptr instances in different
>> threads is fine. The example states that you can't, in thread B, destroy the
>> shared_ptr which thread A copies (*sp_Session in your code).
>>
>> [...]
>
> Peter,
> can you please give an example how that can happen, given the shared_counter
> is atomic. I thought the counter is first incremented than the rest of the
> machinery deals with pointer copying etc. and in case of underlying object
> destruction, the counter is first decremented and than the object is
> destroyed. How is that possible, that shared_counter reaches 0, destructor
> is called and afterwards the underlying pointer will be assigned to the new
> shared instance?
> With Kind Regards,
> Ovanes
>

He means that while the reference count is thread safe, the pointer is
not. Here's an example that will cause problems:

Thread A: ptr1 = ptr2;
Thread B: ptr2 = ptr;

Note that ptr2 is being concurrently read and modified.

Here's an example that safely modifies only the reference count. No
pointers are written to concurrently:

Thread A: ptr1 = ptr;
Thread B: ptr2 = ptr; ptr2.reset();

-- 
Cory Nelson
http://int64.org

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net