title: c++11 atomic<int>++ much slower than std::mutex protected int++, why?
body: <p>To compare the performance difference between <code>std::atomic&lt;int&gt;</code>++ and <code>std::mutex</code> protected <code>int</code>++, I have this test program:</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;atomic&gt;
  #include &lt;mutex&gt;
  #include &lt;thread&gt;
  #include &lt;chrono&gt;
  #include &lt;limits&gt;
  using namespace std;
  #ifndef INT_MAX
  const int INT_MAX = numeric_limits&lt;std::int32_t&gt;::max();
  const int INT_MIN = numeric_limits&lt;std::int32_t&gt;::min();
  #endif
  using std::chrono::steady_clock;
  const size_t LOOP_COUNT = 12500000;
  const size_t THREAD_COUNT = 8;
  int intArray[2] = { 0, INT_MAX };
  atomic&lt;int&gt; atomicArray[2];
  void atomic_tf() {//3.19s
      for (size_t i = 0; i &lt; LOOP_COUNT; ++i) {
          atomicArray[0]++;
          atomicArray[1]--;
      }
  }
  mutex m;
  void mutex_tf() {//0.25s
      m.lock();
      for (size_t i = 0; i &lt; LOOP_COUNT; ++i) {
          intArray[0]++;
          intArray[1]--;
      }
      m.unlock();
  }
  int main() {
      {
          atomicArray[0] = 0;
          atomicArray[1] = INT_MAX;
          thread tp[THREAD_COUNT];
          steady_clock::time_point t1 = steady_clock::now();
          for (size_t t = 0; t &lt; THREAD_COUNT; ++t) {
              tp[t] = thread(atomic_tf);
          }
          for (size_t t = 0; t &lt; THREAD_COUNT; ++t) {
              tp[t].join();
          }
          steady_clock::time_point t2 = steady_clock::now();
          cout &lt;&lt; (float)((t2 - t1).count()) / 1000000000 &lt;&lt; endl;
      }
      {
          thread tp[THREAD_COUNT];
          steady_clock::time_point t1 = steady_clock::now();
          for (size_t t = 0; t &lt; THREAD_COUNT; ++t) {
              tp[t] = thread(mutex_tf);
          }
          for (size_t t = 0; t &lt; THREAD_COUNT; ++t) {
              tp[t].join();
          }
          steady_clock::time_point t2 = steady_clock::now();
          cout &lt;&lt; (float)((t2 - t1).count()) / 1000000000 &lt;&lt; endl;
      }
      return 0;
  }
  </code></pre>
  <p>I ran this program on windows/linux many times (compiled with clang++14, g++12), basically same result.</p>
  <ol>
  <li><p><code>atomic_tf</code> will take 3+ seconds</p>
  </li>
  <li><p><code>mutex_tf</code> will take 0.25+ seconds.</p>
  </li>
  </ol>
  <p>Almost 10 times of performance difference.</p>
  <p>My question is, if my test program is valid, then does it indicate that using atomic variable is much more expensive compared with using mutex + normal variables?</p>
  <p>How does this performance difference come from?
  Thanks!</p>