title: How to use std::atomic efficiently
body: <p>std::atomic is new feature introduced by c++11 but I can't find much tutorial on how to use it correctly.  So are the following practice common and efficient?</p>
  
  <p>One practice I used is we have a buffer and I want to CAS on some bytes, so what I did was:</p>
  
  <pre><code>uint8_t *buf = ....
  auto ptr = reinterpret_cast&lt;std::atomic&lt;uint8_t&gt;*&gt;(&amp;buf[index]);
  uint8_t oldValue, newValue;
  do {
    oldValue = ptr-&gt;load();
    // Do some computation and calculate the newValue;
    newValue = f(oldValue);
  } while (!ptr-&gt;compare_exchange_strong(oldValue, newValue));
  </code></pre>
  
  <p>So my questions are:</p>
  
  <ol>
  <li>The above code uses ugly reinterpret_cast and is this the correct way to retrieve the atomic pointer that reference to the location &amp;buf[index]?</li>
  <li>Is the CAS on a single byte significantly slower than CAS on a machine word, so that I should avoid using it?  My code will look more complicated if I change it to load a word, extract the byte, compute and set the byte in the new value, and do CAS.  This makes the code more complicated and I also need to deal with address alignment myself.</li>
  </ol>
  
  <p>EDIT: if those questions are processor/architecture dependent, then what's the conclusion for x86/x64 processors?</p>