title: Is my spin lock implementation correct and optimal?
body: <p>I'm using a spin lock to protect a very small critical section. Contention happens <em>very</em> rarely so a spin lock is more appropriate than a regular mutex.</p>
  
  <p>My current code is as follows, and assumes x86 and GCC:</p>
  
  <pre><code>volatile int exclusion = 0;
  
  void lock() {
      while (__sync_lock_test_and_set(&amp;exclusion, 1)) {
          // Do nothing. This GCC builtin instruction
          // ensures memory barrier.
      }
  }
  
  void unlock() {
      __sync_synchronize(); // Memory barrier.
      exclusion = 0;
  }
  </code></pre>
  
  <p>So I'm wondering:</p>
  
  <ul>
  <li>Is this code correct? Does it correctly ensure mutual exclusion?</li>
  <li>Does it work on all x86 operating systems?</li>
  <li>Does it work on x86_64 too? On all operating systems?</li>
  <li>Is it optimal?
  
  <ul>
  <li>I've seen spin lock implementations using compare-and-swap but I'm not sure which is better.</li>
  <li>According to the GCC atomic builtins documentation (<a href="http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Atomic-Builtins.html" rel="noreferrer">http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Atomic-Builtins.html</a>) there's also <code>__sync_lock_release</code>. I'm not an expert on memory barriers so I'm not sure whether it's okay for me to use this instead of <code>__sync_synchronize</code>.</li>
  <li>I'm optimizing for the case in which there's no contention.</li>
  </ul></li>
  </ul>
  
  <p>I do not care <em>at all</em> about contention. There may be 1, maybe 2 other threads trying to lock the spin lock once every few <em>days</em>.</p>