title: gcc atomic built-in functions
body: <p><a href="http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Atomic-Builtins.html">http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Atomic-Builtins.html</a></p>
  
  <p>I believe that the following code increases the value of var atomically.</p>
  
  <pre><code>volatile int var = 0;
  __sync_fetch_and_add( &amp;var, 1 )
  </code></pre>
  
  <p>I understood the above codes as the following <strong>logic</strong>:</p>
  
  <ol>
  <li>Load the address of variable var</li>
  <li>write number 1 onto variable var atomically   - through register/cache, somehow</li>
  </ol>
  
  <p>However, I doubt if the following is atomic, too</p>
  
  <pre><code>volatile int var = 0;
  volatile int num = 1;
  __sync_fetch_and_add( &amp;var, num )
  </code></pre>
  
  <p>Since it may be interpreted as </p>
  
  <ol>
  <li>Load the address of variable var</li>
  <li>Load the value of variable num into a register</li>
  <li>write the value onto variable var.</li>
  </ol>
  
  <p>After #2 is executed, but before #3,
  the CPU/thread gets interrupted and another CPU/thread updates
  the value of variable num.</p>
  
  <p>In other words,
  when using _<em>sync</em>*() of gcc,
  can I use a variable, not a constant, as the second argument?</p>
  
  <p>Doesn't it break the atomicity?</p>