Re: [boost] boost::shared_ptr<>::compare_and_swap() -- AmIinsaneforwanting this?

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?
Peter Dimov wrote:
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.
I apologize if this is rapidly becoming a refresher course for me in multithreaded programming. ;^) Forgetting about compare-and-swap for a second, what you're saying is that the _initialization_ of px2 from px in thread A above is not atomic? Is this sequence atomic? // Before the treads start shared_ptr<X> px(blah); // thread A shared_ptr<X> px2; px2 = px; // thread B px = px3 I thought that constructors, destructors and the assignments were atomic from the documentation, but it doesn't mean I'm reading it right. I'm reading http://www.boost.org/libs/smart_ptr/compatibility.htm. Under "Features That Improve Robustness" it says "The manipulation of use counts is now thread safe on Windows, Linux and platforms that support pthreads. See <boost/detail/atomic_count.hpp> file for details." I really don't understand, based upon that statement and the statements made in the comments of atomic_count.hpp of exactly what operations are thread safe and what aren't when using shared_ptr. I'm sorry if I'm being too dense here. I think a section in the documentation saying exactly what is guaranteed and what isn't would help a lot. -- George T. Talbot gtalbot@locuspharma.com

Talbot, George wrote:
I'm sorry if I'm being too dense here. I think a section in the documentation saying exactly what is guaranteed and what isn't would help a lot.
Here you go: http://boost.org/libs/smart_ptr/shared_ptr.htm#ThreadSafety
participants (2)
-
Peter Dimov
-
Talbot, George