[cpp-threads] Failed compare-and-swap

Doug Lea dl at cs.oswego.edu
Wed Aug 1 19:50:11 BST 2007


Boehm, Hans wrote:

> 
> FWIW, java.lang.concurrent.atomic.compareAndSet returns only a Boolean.
> But (unlike weakCompareAndSet) it may not fail spuriously, and hence I
> think still needs acquire semantics in the failure case 
> 

Yes.

FWIW, I've often written code in which CAS failure is used
informatively. As in, for example, part of a basic exchanger

   while(!slot.cas(null, myItem)) { // slot was not empty
      otherCode();
      otherItem = slot.get();
      if (slot.cas(otherItem, null))
         return otherItem;
   }
   etc.

It would in general be a Bad Idea for "otherCode()" to get reordered here,
since it is intended to execute only if at some point the slot
was in fact not empty. It would be weird at best to *require* a
test-and-test-and-set here
   while(slot.get() != null || !slot.cas(null, myItem)) ...
if for no other reason that the requirement would be far too
subtle for most programmers to get right reliably.

For fallible/weak-CAS, I can see a case for allowing reordering.

-Doug



More information about the cpp-threads mailing list