title: C++ threads race condition simulation
body: <p>Here is a C++ program that runs <code>10</code> times with <code>5</code> different threads and each thread increments the <code>value</code> of <code>counter</code> so the final output should be <code>500</code>, which is exactly what the program is giving output. But i cant understand why is it giving <code>500</code> every time the output should be different as the increment operation is not <code>atomic</code> and there are no locks used so the program should give out different outputs in each case.</p>
  
  <p>edit to increase probability of race condition i increased the loop count but still couldn't see any varying output</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;thread&gt;
  #include &lt;vector&gt;
  
  struct Counter {
      int value;
  
      Counter() : value(0){}
  
      void increment(){
          value = value + 1000;
      }
  };
  
  int main(){
      int n = 50000;
      while(n--){
      Counter counter;
  
      std::vector&lt;std::thread&gt; threads;
      for(int i = 0; i &lt; 5; ++i){
          threads.push_back(std::thread([&amp;counter](){
              for(int i = 0; i &lt; 1000; ++i){
                  counter.increment();
              }
          }));
      }
  
      for(auto&amp; thread : threads){
          thread.join();
      }
  
      std::cout &lt;&lt; counter.value &lt;&lt; std::endl;
      }
      return 0;
  }
  </code></pre>