Boost logo

Boost :

From: Christophe Meessen (christophe_at_[hidden])
Date: 2002-05-03 07:58:35


Hello,

I found boost while I was searching for a thread safe reference countig
pointer.
I had my own but after closer study I noticed that it is not thread
safe.

The problem is not in protecting counter increment and decrement, but
when destroying the object.

The problem is the following.

Suppose three threads attempting to do something on the shared_ptr.
T1 is first and access the protected counter.
T2 arrives just then, and is executing reset(). So it blocks on the
mutex and waits for T1 to complete its operation.
The T3 arrives and copies the shared_ptr to another one, so it should
increment.

When T1 leaves, T2 executes and decrement the counter that reaches 0
while T3 is waiting and planned to increment it.

A stupid implementation would destroy the object once the counter
reaches 0. Thus T2 would delete the object although T3 is waiting on the
mutex and in fact was planning to increment the counter.

This can happen if the shared_ptr is a class member variable and is
accessed by threads.

>From my analysis I came to the conclusion that it was not possible to
make the shared_ptr concept thread safe.

So I read the news that shared_ptr was made thread safe in boost. I am a
bit surprised. Did I make a mistake in my reasoning. Is it really thread
safe ?

-- 
Ch. Meessen

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