Subj : Re: A question about atomic_ptr To : comp.programming.threads From : Joe Seigh Date : Thu Apr 14 2005 07:20 pm On Fri, 15 Apr 2005 00:42:08 +0300, Peter Dimov wrote: > Joe Seigh wrote: >> On Thu, 14 Apr 2005 16:53:13 +0300, Peter Dimov >> wrote: >>> You mean the race between >>> >>> atomic_ptr p2( p1 ); >>> >>> and >>> >>> p1 = 0; >>> >>> ? >> >> Yes. > > I must be missing something because I think this can be fixed easily: > > atomic_ptr<>::assign( atomic_ptr & other ) // other is unshared > > atomic_ptr temp( *this ); > > atomically set *this to other > set other to empty > > // destroy temp > > The 'atomically set *this to other' is hard for shared_ptr because it stores > two pointers, but not a problem for a single pointer implementation. > > operator=( atomic_ptr const & other ) is of course > > atomic_ptr temp( other ); > this->assign( other ); > > What am I missing? > It's not broke at least as far as atomic_ptr is concerned. As long as you have a thread-safe copy ctor and an atomic swap, it's straight forward. atomic_ptr & operator=(atomic_ptr & src) { atomic_ptr temp(src); swap(temp); return *this; } Swap atomically sets *this to the new value and temp to the old value. When temp goes out of scope, it dtors the old value. The tricky stuff is in the copy ctor and depends on what trick you're using to safely increment the reference count. I don't use const on the src because some implementations change the source ptr and there's memory barriers so your not getting much optmization anyway. It also can be this which I didn't use because vc++ gave me problems. Pass by value copies the source so it's equivalent to above. atomic_ptr & operator=(atomic_ptr src) { swap(src); return *this; } This is pretty generic operator=. You could use any type with copy ctor and swap method here. But like I said, the tricky bits are elsewhere and there it's more of an algorithm rather than a c++ thing. -- Joe Seigh .