title: Why does code mutating a shared variable across threads apparently NOT suffer from a race condition?
body: <p>I'm using Cygwin GCC and run this code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;thread&gt;
  #include &lt;vector&gt;
  using namespace std;
  
  unsigned u = 0;
  
  void foo()
  {
      u++;
  }
  
  int main()
  {
      vector&lt;thread&gt; threads;
      for(int i = 0; i &lt; 1000; i++) {
          threads.push_back (thread (foo));
      }
      for (auto&amp; t : threads) t.join();
  
      cout &lt;&lt; u &lt;&lt; endl;
      return 0;
  }
  </code></pre>
  
  <p>Compiled with the line: <code>g++ -Wall -fexceptions -g -std=c++14 -c main.cpp -o main.o</code>.</p>
  
  <p>It prints 1000, which is correct. However, I expected a lesser number due to threads overwriting a previously incremented value. Why does this code not suffer from mutual access?</p>
  
  <p>My test machine has 4 cores, and I put no restrictions on the program that I know of.</p>
  
  <p>The problem persists when replacing the content of the shared <code>foo</code> with something more complex, e.g.</p>
  
  <pre><code>if (u % 3 == 0) {
      u += 4;
  } else {
      u -= 1;
  }
  </code></pre>