Subj : Re: A question about atomic_ptr To : comp.programming.threads From : Peter Dimov Date : Fri Apr 15 2005 02:52 am Joe Seigh wrote: > On Fri, 15 Apr 2005 00:42:08 +0300, Peter Dimov > wrote: >> 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. The point is that you no longer need tricks in the copy constructor. The original race is only a problem when the count is 1 so that you can have the assignment destroy the count and then the copy constructor attempt to increment it. The modified version avoids this because the count is always at least two at the race because of 'temp'. .