title: How to atomically negate an std::atomic_bool?
body: <p>The naive boolean negation</p>
  
  <pre><code>std::atomic_bool b;
  b = !b;
  </code></pre>
  
  <p>does not seem to be atomic. I suspect this is because <code>operator!</code> triggers a cast to plain <code>bool</code>. How would one atomically perform the equivalent negation? The following code illustrates that the naive negation isn't atomic:</p>
  
  <pre><code>#include &lt;thread&gt;
  #include &lt;vector&gt;
  #include &lt;atomic&gt;
  #include &lt;iostream&gt;
  
  typedef std::atomic_bool Bool;
  
  void flipAHundredThousandTimes(Bool&amp; foo) {
    for (size_t i = 0; i &lt; 100000; ++i) {
      foo = !foo;
    }
  }
  
  // Launch nThreads std::threads. Each thread calls flipAHundredThousandTimes 
  // on the same boolean
  void launchThreads(Bool&amp; foo, size_t nThreads) {
  
    std::vector&lt;std::thread&gt; threads;
    for (size_t i = 0; i &lt; nThreads; ++i) {
      threads.emplace_back(flipAHundredThousandTimes, std::ref(foo));
    }
  
    for (auto&amp; thread : threads) thread.join();
  
  }
  
  int main() {
  
    std::cout &lt;&lt; std::boolalpha;
    Bool foo{true};
  
    // launch and join 10 threads, 20 times.
    for (int i = 0; i &lt; 20; ++i) {
      launchThreads(foo, 10);
      std::cout &lt;&lt; "Result (should be true): " &lt;&lt; foo &lt;&lt; "\n";
    }
  
  }
  </code></pre>
  
  <p>The code launches 10 threads, each of which flips the atomic_bool a larrge, even, number of times (100000), and prints out the boolean. This is repeated 20 times. </p>
  
  <p><strong>EDIT</strong>: For those who want to run this code, I am using a GCC 4.7 snapshot on ubuntu 11.10 with two cores. The compilation options are:</p>
  
  <pre><code>-std=c++0x -Wall -pedantic-errors -pthread
  </code></pre>