Re: [boost] boost::shared_ptr<>::compare_and_swap() -- Am I insaneforwanting this?

Talbot, George wrote:
Hi,
I have a question for the designers and implementers of boost::shared_ptr:
Is there any plan afoot to support lock-free programming using shared_ptr? I was fooling around with wanting to attempt lock-free update of a tree structure that I have that uses shared_ptr. If no-one's thinking about this, how might I go about implementing:
bool boost::shared_ptr<T>::compare_and_swap(T* original, shared_ptr<T>& new_one)
Peter Dimov wrote:
Very, very difficult. :-) shared_ptr is not atomic;
I can pass a shared_ptr between threads right now, correct?
you can look at Joe Seigh's atomic_ptr:
http://atomic-ptr-plus.sourceforge.net/
and Chris Thomasson's
http://appcore.home.comcast.net/vzoom/refcount/
for examples of atomic reference counted pointers.
Shared_ptr can be made atomic by using a spinlock. This isn't really lock-free, though.
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? I can see where compare_and_swap() probably can't be added without adding a sequence number. Am I right saying that this is one of the reasons adding this to shared_pointer isn't realistic? -- George T. Talbot <gtalbot@locuspharma.com>

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.
participants (2)
-
Peter Dimov
-
Talbot, George