Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2006-11-10 09:53:21


Talbot, George wrote:

> I thought that the current implementation of shared_ptr is lock-free
> and multithreaded in the sense that I can pass shared_ptr between
> threads, and the reference count is updated correctly, etc. (I'm
> using BOOST 1.33.) Am I incorrect in thinking this?

This is not the same as atomic. An atomic type allows you to modify a
variable from thread A while, at the same time, thread B is also reading or
writing it. shared_ptr doesn't offer this level of thread-safety. As an
example, consider:

shared_ptr<X> px;

// thread A

shared_ptr<X> px2( px );

// thread B

px = px3;

(you can also have thread B doing compare and swap, it doesn't matter.)

Imagine that thread A reads the two pointers from px and is preempted right
after that. Thread B overwrites the contents of px, and in doing so, causes
its reference count to drop to zero; the object and the control block are
destroyed. Thread A wakes up and attempts to increment the now non-existent
reference count. Bad things happen.

But maybe I'm misunderstanding the intent of your compare and swap
primitive.


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