Boost logo

Boost Users :

From: gast128 (gast128_at_[hidden])
Date: 2007-08-06 10:56:08


Ovanes Markarian <om_boost <at> keywallet.com> writes:

>
> Ok, just looking at the example will bring more light into your questions.
>
> First non-safe scenario:
> // thread A
> p = p3; // reads p3, writes p
>
> // thread B
> p3.reset(); // writes p3; undefined, simultaneous read/write
>
> Either thread B is executed before thread A, then you assign empty shared
pointer in thread A (to
> prior pointer deletion in thread B) OR thread A is executed before thread B,
then a valid pointer
> is assigned in B. Possible scenario here as well: Value of p3 is read,
scheduler switches to
> thread B; deletes pointer owned by p3; switches back to thread A and
assignes invalid pointer
> value to p (deletion of pointee can happen probably twice and it is also
undefined what is in
> memory at the point of assignment and what will be written later on...)
> ...
> Ovanes Markarian

This should mean that shared_ptr is not at all thread safe, as in above race
condition. I am not sure if this contradicts the quote 'shared_ptr objects
offer the same level of thread safety as built-in types', it at least does not
address the thread safety of the unique reference counting feature (which has
no analog for 'normal' pointers).

The atomic increment and decrement ref counting then only work for a shared
const shared pointer:

void g(boost::shared_ptr<const B> ptr)
{
   //...
}

void f()
{
  boost::shared_ptr<const B> ptr(new B);

  //give ptr to threads
  boost::thread thrd1(boost::bind(&g, ptr));
  boost::thread thrd2(boost::bind(&g, ptr));

  //fire and forget
  ptr.reset();
}

However they finally end up in a dtor call which according to the
documentation is an legal or illegal write operation.


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