Boost logo

Boost Users :

Subject: Re: [Boost-users] Thread Safety of shared_ptr
From: Kevin Frey (kfrey_at_[hidden])
Date: 2011-05-02 20:46:39


> Actually, I am not sure with this statement. Destructor is only called
if shared count reaches zero. I don't think that this can happen, that a
dtor is called in one thread and the other thread is still able to
increment the shared count even from the weak_ptr. I remember reading
weak_ptr's source and saw that it is also protected again such a case.

 

I have taken the example at face value, but in hindsight the examples
could be a lot better because there is no context to describe the
circumstances of how the shared_ptrs are instantiated.

 

For example, is p allocated globally, and p2 & p3 allocated at the
beginning of their respective threads? If so, example 4 becomes
meaningless because Thread B cannot force p2 out of scope since it would
only go out of scope once thread A exits, since thread A controls the
scope of p2. If thread B were to force p2 "out of scope" then p2 would
have to be a shared_ptr< >*, dynamically allocated., and subsequently
deleted by Thread B. But it is not represented that way.

 

Unfortunately none of this helps solve my original question, which given
the direction this thread is proceeding, I will re-state in pseudo-code
that approximates the *actual* situation occurring in my program:

 

Earlier on:

 

shared_ptr< Session >* sp_Session = new shared_ptr< Session >( new
Session );

 

Dependent_Class* dep = new Dependent_Class( shared_ptr< Session >&
shared_ptr_session );

In Dependent_Object::Dependent_Object( )

   this->sp_Session = new shared_ptr< Session >( shared_ptr_session );

Now, simultaneously:

 

Thread A:

Dependent_Class* dep2 = new Dependent_Class( shared_ptr< Session>&
shared_ptr_session );

In Dependent_Object::Dependent_Object( )

   this->sp_Session = new shared_ptr< Session >( shared_ptr_session );

 

Thread B:

In Dependent_Class::~Dependent_Class( ): // the cleanup of dep

   delete this->sp_Session;

 

So, we have:

 

1. A shared object (pointed to by a shared_ptr) that is presently
in existence with a reference count of at least 2.

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.

 

Note that the shared object is *not being destroyed* here, just the
reference counts are being manipulated.

 

Will shared_ptr handle this situation correctly?

 

Thanks

 

Kevin

 

 



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