title: Basic usage of conditionals with std::atomic<T>
body: <p>So I'm starting to familiarize myself with C++11 <code>&lt;atomic&gt;</code> types.  In the past, when I had an atomic flag I would usually simply lock a mutex before accessing it.  A common need would be to check if the flag is <code>false</code>, and if so, atomically set it to <code>true</code> and then do something.  So basically this would be accomplished like this, where <code>flag</code> is a simple <code>bool</code>:</p>
  
  <pre><code>{
      std::lock_guard&lt;std::mutex&gt; lock(my_mutex);
      if (!flag) 
      {
          flag = true;
          // do something;
      }
  }
  </code></pre>
  
  <p>So, now I'm trying to figure out how the same thing can be accomplished with <code>&lt;atomic&gt;</code>.  The <a href="http://en.cppreference.com/w/cpp/atomic/atomic" rel="noreferrer"><strong>docs</strong></a> say that the assignment operator and <code>operator T</code> of an atomic type are atomic operations.  However, if I change <code>flag</code> to <code>std::atomic&lt;bool&gt;</code>, I imagine I can't simple say:</p>
  
  <pre><code>if (!flag)
  {
    flag = true;
    // do something
  }
  </code></pre>
  
  <p>... because even though the expression <code>(!flag)</code> is atomic, and the assignment <code>flag = true</code> is atomic, there's nothing to prevent another thread from modifying flag in between those two statements.</p>
  
  <p>So, if I understand correctly here, the only proper usage - <strong><em>at all</em></strong> - of conditionals with atomic types, where the result of the conditional could modify the atomic variable, is to use the Compare and Swap operation?  Am I correct?</p>
  
  <p>So, I'd have to say:</p>
  
  <pre><code>bool expected = false;
  if (flag.compare_exchange_weak(expected, true))
  {
     // do something
  }
  </code></pre>
  
  <p>Am I correct in my understanding here?</p>