[cpp-threads] Failed compare-and-swap

Paul E. McKenney paulmck at linux.vnet.ibm.com
Tue Jul 31 19:12:58 BST 2007


On Tue, Jul 31, 2007 at 07:56:29PM +0200, Alexander Terekhov wrote:
> On 7/31/07, Herb Sutter <hsutter at microsoft.com> wrote:
> > Paul wrote:
> > > Successful CAS has the specified memory-ordering properties.  The
> > > strong-atomics CAS would have a full fence when successful.  A given
> > > weak-atomics CAS would have the specified memory-ordering properties,
> > > for example, a relaxed CAS would have no memory-ordering properties.
> >
> > Right, when I said full fence semantics I meant for strong atomics.
> 
> I just wonder whether you realize the cost of "full fence" strong
> atomic semantics for CAS on Power and other stuff ala Xbox. ;-)
> 
> It's actually dual fenced (with most expensive "sync" fence for
> leading and trailing barriers) and always-write (even in failure case)
> semantics.

Yes, it is quite expensive on POWER and other weakly ordered machines.
However: (1) in most algorithms, CAS failure is infrequent, and (2) in those
cases where failure is frequent, assuming they exist, the programmer
can do a relaxed CAS and then use explicit memory fences if needed.

> > > There are algorithms in which a failed CAS plays a role similar to a
> > > failed trylock.  So it would make quite a bit of sense for a failed CAS
> > > to have the same memory-ordering semantics that it would have had if
> > > successful.  After all, the common case should be successful CAS!  ;-)
> >
> > Sorry if the answer is obvious: What are some cases where a failed trylock
> > needs ordering semantics?
> 
> Nothing portable under ISO/IEC 9945.
> 
> "Unless explicitly stated otherwise, if one of the above functions
> returns an error, it is unspecified whether the invocation causes
> memory to be synchronized."
> 
> pthread_mutex_trylock() doesn't fall under "explicitly stated otherwise".

Sounds like we need to make sure that we should either define CAS to
have two modes of "success", or to get CAS to explicitly state otherwise
should it ever be added to ISO/IEC 9945.  Might be nice to get the
pthread_mutex_trylock() primitive to be added to the list of "explicitly
stated otherwise" primitives, but that doesn't sound like a short-term
project.  ;-)

						Thanx, Paul



More information about the cpp-threads mailing list