title: Easiest way to implement shared integer counter in C++11 without mutexes:
body: <p>Suppose we have the following code which counts the number of times something occurs:</p>
  
  <pre><code>int i=0;
  void f() {
     // do stuff  . . .
     if(something_happens) ++i;
  }
  
  int main() {
      std::vector&lt;std::thread&gt; threads;
      for(int j = 0; j&lt; std::thread::hardware_concurrency(); ++j) {
          threads.push_back(std::thread(f));
      }
  
      std::for_each(threads.begin(), threads.end(), std::mem_fn(&amp;std::thread_join));
      std::cout &lt;&lt; "i = " &lt;&lt; i &lt;&lt; '\n';
  }
  </code></pre>
  
  <p>As it stands there is a clear race condition on i. Using C++11, what is (1) the easiest method for eliminating this race condition, and (2) the fastest method?, preferably without using mutexes. Thanks.</p>
  
  <p>Update: Using the comment to use atomics, I got a working program which compiles under the Intel Compiler, version 13: </p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;thread&gt;
  #include &lt;vector&gt;
  #include &lt;atomic&gt;
  #include &lt;algorithm&gt;
  
  std::atomic&lt;unsigned long long&gt; i = 0;
  
  void f(int j) {
      if(j%2==0) {
          ++i;
      }  
  }
  
  int main() {
      std::cout &lt;&lt; "Atomic i = " &lt;&lt; i &lt;&lt; "\n";
      int numThreads = 8; //std::thread::hardware_concurrency() not yet implemented by Intel
      std::vector&lt;std::thread&gt; threads;
      for(int k=0; k&lt; numThreads; ++k) {
          threads.push_back(std::thread(f, k));
      }
  
      std::for_each(threads.begin(), threads.end(), std::mem_fn(&amp;std::thread::join));
          std::cout &lt;&lt; "Atomic i = " &lt;&lt; i &lt;&lt; "\n";
      }
  </code></pre>