|
Boost : |
From: Peter Dimov (pdimov_at_[hidden])
Date: 2005-02-13 08:17:36
Puneet Jain wrote:
> I am a new user of boost pointers and was wondering
> about the thread safety in boost shared and intrusive
> pointers.
>
> After reading some eariler posts and the current
> documentation, I am little confused. As per current
> documentation shared pointers thread safety in shared
> pointers is on the lines of STL and thus they are not
> thread safe for writing. But I am pretty sure I read
> in one of the posts that shared pointer is thread safe
> for all operations. Also, looking at the operator= and
> swap, it seems there could be some thread safety
> issues.
shared_ptr offers "basic thread safety", also known as "as thread safe as an
int". These are the same guarantees that the POSIX memory model gives for
built-int types such as int: concurrent reads are safe, concurrent writes to
different objects are safe.
"Strong thread safety" (concurrent writes, concurrent reads+writes are safe)
is more expensive, harder to implement, and hard to use correctly. Consider
this code:
// thread A
p.get();
// thread B
p.reset();
This is obviously invalid under basic: p.reset() writes p. But it is also
invalid under strong: p.reset() may delete the pointer returned by p.get()
in mid-flight, which according to the standard is undefined behavior (and on
some mainframes even looking at such a pointer causes a hardware trap.) A
less exotic example could be
Base * q = p.get(); // p.get() returns a Derived*
or
p->f();
both of which may fail on "ordinary" hardware.
> Also, I have my own counted_base which I use in
> intrusive pointer. If my understanding is correct, to
> ensure thread safety, if I ensure add_ref and
> release_ref operations are atomic, I am pretty much
> covering all the bases.
If by "thread safety" you mean "strong thread safety", then no.
intrusive_ptr hasn't been designed for strong thread safety. By changing
swap() to use three atomic exchanges you may be able to achieve strong
thread safety, but I haven't verified this in detail.
Are you sure that you need strong thread safety?
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk