title: Why my std::atomic<int> variable isn't thread-safe?
body: <p>I don't know why my code isn't thread-safe, as it outputs some inconsistent results. </p>
  
  <pre><code>value 48
  value 49
  value 50
  value 54
  value 51
  value 52
  value 53
  </code></pre>
  
  <p>My understanding of an atomic object is it prevents its intermediate state from exposing, so it should solve the problem when one thread is reading it and the other thread is writing it. </p>
  
  <p>I used to think I could use std::atomic without a mutex to solve the multi-threading counter increment problem, and it didn't look like the case. </p>
  
  <p>I probably misunderstood what an atomic object is, Can someone explain?</p>
  
  <pre class="lang-cpp prettyprint-override"><code>void
  inc(std::atomic&lt;int&gt;&amp; a)
  {
    while (true) {
      a = a + 1;
      printf("value %d\n", a.load());
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
  }
  
  int
  main()
  {
    std::atomic&lt;int&gt; a(0);
    std::thread t1(inc, std::ref(a));
    std::thread t2(inc, std::ref(a));
    std::thread t3(inc, std::ref(a));
    std::thread t4(inc, std::ref(a));
    std::thread t5(inc, std::ref(a));
    std::thread t6(inc, std::ref(a));
  
    t1.join();
    t2.join();
    t3.join();
    t4.join();
    t5.join();
    t6.join();
    return 0;
  }
  </code></pre>