title: atomic swap with CAS (using gcc sync builtins)
body: <p>Can the compare-and-swap function be used to swap variables atomically? 
  I'm using C/C++ via gcc on x86_64 RedHat Linux, specifically the __sync builtins. 
  Example:</p>
  
  <pre><code>   int x = 0, y = 1; 
     y = __sync_val_compare_and_swap(&amp;x, x, y);
  </code></pre>
  
  <p>I think this boils down to whether x can change between &amp;x and x; for instance, if &amp;x constitutes an operation, it might be possible for x to change between &amp;x and x in the arguments. I want to assume that the comparison implicit above will always be true; my question is whether I can. Obviously there's the bool version of CAS, but then I can't get the old x to write into y.</p>
  
  <p>A more useful example might be inserting or removing from the head of a linked list (gcc claims to support pointer types, so assume that's what elem and head are):</p>
  
  <pre><code>   elem-&gt;next = __sync_val_compare_and_swap(&amp;head, head, elem); //always inserts?
     elem = __sync_val_compare_and_swap(&amp;head, head, elem-&gt;next); //always removes?
  </code></pre>
  
  <p>Reference:
  <a href="http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html" rel="noreferrer">http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html</a></p>