Boost logo

Boost :

From: bill_kempf (williamkempf_at_[hidden])
Date: 2002-02-11 10:54:44


--- In boost_at_y..., "Peter Dimov" <pdimov_at_m...> wrote:
> From: "bill_kempf" <williamkempf_at_h...>
> > I'm unconvinced that weak_ptr<> is useful in a MT program.
>
> Who's trying to convince you otherwise? ;-)
>
> > At least
> > not if ANY of the pointers (shared_ptr<> or weak_ptr<>) are shared
> > across thread boundaries.
>
> More precisely, not if the last shared_ptr that owns the object may
be
> destroyed by a different thread.
>
> Shared and weak pointers are typically not shared between threads;
usually a
> copy is passed to the other thread.

Yes, that's actually what I had in mind. I did a very poor job of
describing it, though ;).

> Still, a weak pointer can be used safely in a multithreaded program
when (a)
> the object is owned by the same thread, i.e. there exists at least
one
> shared_ptr that is guaranteed to be destroyed by the current
thread, or (b)
> when the user locks appropriately.

Just having a shared_ptr<> that will be destroyed by the thread isn't
enough. That pointer can be destroyed before the weak_ptr<>s and put
you right back into the same situation where you can't tell if the
object has been destroyed (asynchronously) using the weak_ptr<>. So
to actually work this way the shared_ptr<> must not be destroyed
before the weak_ptr<>, but then most of the utility of weak_ptr<> is
removed. We might as well be using a raw pointer.

> > A redesign might help. If the weak_ptr<>'s only functionality was
> > conversion to a shared_ptr<> where you'd get a NULL shared_ptr<>
if
> > the object were gone, you wouldn't have the above problem.
However,
> > it wouldn't be efficient either (and would be danged difficult to
> > implement).
>
> The usual choice. Is the user responsible for synchronization,
yielding
> performance, or is the implementation, yielding safety (at a price
that many
> would find unbearable.)

I'm likely just missing something, but I don't see how the user can
do the synchronization here. The "mutex" or other ref-counting
mechanisms are contained in an object that will be destroyed
asynchronously. Attempts to synchronize through the weak_ptr<>
instance have the same race condition as all other accesses. Unless
you plan to use a global synch object for all accesses, but that's
very inefficient.

> Unfortunately there is no portable "check if zero, increment only
if not
> zero, return the previous value" atomic operation AFAIK.

I'm not sure how such an operation would help.

Bill Kempf


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