title: Why is std::mutex faster than std::atomic?
body: <p>I want to put objects in <code>std::vector</code> in multi-threaded mode. So I decided to compare two approaches: one uses <code>std::atomic</code> and the other <code>std::mutex</code>. I see that the second approach is faster than the first one. Why? </p>
  
  <p>I use GCC 4.8.1 and, on my machine (8 threads), I see that the first solution requires <code>391502</code> microseconds and the second solution requires <code>175689</code> microseconds.</p>
  
  <pre><code>#include &lt;vector&gt;
  #include &lt;omp.h&gt;
  #include &lt;atomic&gt;
  #include &lt;mutex&gt;
  #include &lt;iostream&gt;
  #include &lt;chrono&gt;
  
  int main(int argc, char* argv[]) {
      const size_t size = 1000000;
      std::vector&lt;int&gt; first_result(size);
      std::vector&lt;int&gt; second_result(size);
      std::atomic&lt;bool&gt; sync(false);
  
      {
          auto start_time = std::chrono::high_resolution_clock::now();
          #pragma omp parallel for schedule(static, 1)
          for (int counter = 0; counter &lt; size; counter++) {
              while(sync.exchange(true)) {
                  std::this_thread::yield();
              };
              first_result[counter] = counter;
              sync.store(false) ;
          }
          auto end_time = std::chrono::high_resolution_clock::now();
          std::cout &lt;&lt; std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(end_time - start_time).count() &lt;&lt; std::endl;
      }
  
      {
          auto start_time = std::chrono::high_resolution_clock::now();
          std::mutex mutex; 
          #pragma omp parallel for schedule(static, 1)
          for (int counter = 0; counter &lt; size; counter++) {
              std::unique_lock&lt;std::mutex&gt; lock(mutex);       
              second_result[counter] = counter;
          }
          auto end_time = std::chrono::high_resolution_clock::now();
          std::cout &lt;&lt; std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(end_time - start_time).count() &lt;&lt; std::endl;
      }
  
      return 0;
  }
  </code></pre>