title: G++ CAS (__sync_val_compare_and_swap) problem needs explaining
body: <p>This is doing my head in.</p>
  
  <p>I'm trying to implement some "lock-free" code and am using CAS (gcc __sync_val_compare_and_swap) to do he heavy lifting.</p>
  
  <p>My problem can be shown with the following code.</p>
  
  <pre><code>volatile bool lock;
  void *locktest( void *arg )
  {
      for ( int i = 0 ; i &lt; 100000 ; ++i )
      {
          // acquire a lock
          while( __sync_val_compare_and_swap( &amp;lock, false, true ) == true )
          {
              // Spin while we don't acquire
          }
  
          // make sure we have the lock
          assert( lock == true );
  
          // release the lock
          assert( __sync_val_compare_and_swap( &amp;lock, true, false ) == true );
      }
  }
  </code></pre>
  
  <p>Ok, if I run the above code in 10 concurrent threads, all is well.</p>
  
  <p>However, if I change the code to read </p>
  
  <pre><code>        // acquire a lock
          while( __sync_val_compare_and_swap( &amp;lock, lock, true ) == true )
  </code></pre>
  
  <p>Notice I've changed "false" to "lock".</p>
  
  <p>All hell breaks loose and the assertion</p>
  
  <pre><code>        // make sure we have the lock
          assert( lock == true );
  </code></pre>
  
  <p>Fires. Can anyone explain why this makes a difference ?</p>
  
  <p>Thx
  Mark.</p>