Subj : Re: A question about atomic_ptr To : comp.programming.threads From : Joe Seigh Date : Thu Apr 14 2005 08:24 pm On Fri, 15 Apr 2005 01:52:19 +0300, Peter Dimov wrote: > Joe Seigh wrote: >> On Fri, 15 Apr 2005 00:42:08 +0300, Peter Dimov >> wrote: >>> 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'. > You have to be able to safely increment the refcount from 1 to 2 in order to "create" the temp. The memory containing the refcount can be reclaimed between the time you load the address of the refcount and when you attempt to increment the refcount. You can't go by what the refcount looks like at the time you attempt to increment it since it could be undefined, meaning it could look like a valid refcount but actually be something else. -- Joe Seigh .