Boost logo

Boost :

From: Richard Damon (rdamon_at_[hidden])
Date: 2002-05-07 08:41:06


> -----Original Message-----
> From: boost-admin_at_[hidden] [mailto:boost-admin_at_[hidden]]On
> Behalf Of Christophe Meessen
> Sent: Tuesday, May 07, 2002 5:38 AM
> To: boost_at_[hidden]
> Subject: Re: [boost] Is shared_ptr really thread safe ?
>
>
> Hello,
>
> Now I am confused. This is really not obvious. Lets try with a concrete
> example:
>
> // declare these two variables as globals.
> shared_ptr<MyData> dataPtr1 = new MyData(), dataPtr2;
>
> // Now whe have the following instruction excuted by two threads T1 and
> T2.
>
> if( rand()%1 )
> dataPtr2 = dataPtr1;
> else
> dataPtr1.reset();
>
> If thread T1 reaches reset() first, but is prehempted just after taking
> the mutex protecting it.
> Then T2 arrives and excute the assignement that should increment the
> counter, but it is of course blocked by the mutex. Thread T1 gets the
> cpu again and execute the reset operation. This should decrement the
> counter that reaches 0 and has the side effect to destroy the object.
> What happens to the counter and mutex ?
>
> In the example you give, the shared_ptr is a local variable so each
> thread has its local copy. In my example the shared_ptr is it self the
> shared resource.
>
...
>
> --
> Bien cordialement,
>
> Ch. Meessen

Your example does not meet the normal conditions required by thread safety
of objects. The only why to meet your requirements is to have every
operation lock before starting and unlock after, this is a cost normally
considered to high for normal programs.

The normal requirements for thread safety let the object assume that it is
only going to be accessed by one thread at a time, so it does not need to
interlock accesses to itself. What it does need to do is to interlock access
to objects it may share with other objects. If an object is shared by more
than one thread it is the responsibility of the threads, not the object, to
synchronize the access. shared_ptr is as thread safe as an object that
doesn't make a special guarantee like being atomic.

For example on many machines the sequence:

(global)
long var1 = 0x12345678;
long var2;

(thread1)

var1 = 0L;

(thread2)

var2 = var1;

on some machines the results in var2 could be, 0x00005678. Does this mean
long is not thread safe, no, it just means long is not atomic.

Atomic types may be accessed, with atomic operations, safely across multiple
threads without the need of external interlocks.

Richard Damon

--
rbrdamon_at_[hidden] (Home)
rdamon_at_[hidden] (Work)

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