title: Avoid race condition when incrementing a counter
body: <p>I have posted on this topic before, but as yet I have not had much luck. I put it down down to a bad question on my part. This time I have made a short compilable example that displays the bad behavior i'm trying to avoid. I hope this is appreciated.</p>
  
  <p>The problem is two (or more) threads are set to run the same process and their "id's" determine which part of the variable data they operate on. Currently both threads will update the counter.</p>
  
  <p>The current output looks like this,</p>
  
  <pre><code>tid = 0, var[tid] = 0
  tid = 0, var[tid] = 1
  tid = 0, var[tid] = 2
  tid = 0, var[tid] = 3
  tid = 0, var[tid] = 4
  tid = 0, var[tid] = 5
  tid = 0, var[tid] = 6
  tid = 0, var[tid] = 7
  tid = 0, var[tid] = 8
  tid = 0, var[tid] = 9
  tid = 1, var[tid] = 0
  Press any key to continue . . .
  </code></pre>
  
  <p>The desired output should be like this...</p>
  
  <pre><code>tid = 0, var[tid] = 0
  tid = 1, var[tid] = 0
  tid = 0, var[tid] = 1
  tid = 1, var[tid] = 1
  tid = 0, var[tid] = 2
  tid = 1, var[tid] = 2
  tid = 0, var[tid] = 3
  tid = 1, var[tid] = 3 etc.
  </code></pre>
  
  <p>Any guidance here would be greatly appreciated.</p>
  
  <p>EDIT: Ive updated the answer with code that works as intended.</p>
  
  <p>[Note that efficiency is important here, I want to complete the process as quickly as possible]</p>
  
  <pre><code>#include &lt;iostream&gt;  
  #include &lt;boost/thread.hpp&gt;
  
  int var[2];
  int mT;
  int mTotalSamples;
  boost::mutex mCountMutex;
  boost::thread *threadMap[2];
  
  using namespace std;
  
  void process()
  {
      int tid = 1;
  
      // sleep for 1 seconds - just to make sure threadMap 
      // has been assigned (only ncessary for this demo).
      boost::this_thread::sleep(boost::posix_time::seconds(1));
  
      if (threadMap[0]-&gt;get_id() == boost::this_thread::get_id()){ tid = 0;}
  
      while ( mT &lt; mTotalSamples ) 
      {
          // perform processing
          var[tid] = mT; 
          // processing complete
  
          mCountMutex.lock(); // (a thread waits to aquire mutex)
          cout &lt;&lt; "tid = " &lt;&lt; tid &lt;&lt; ", var[tid] = " &lt;&lt; var[tid] &lt;&lt; endl;
          mT++;           // How to stop both threads incrementing this?      
          mCountMutex.unlock();       
      }   
  }
  
  int main()
  {
      boost::thread_group threads;
  
      mT = 0;
      mTotalSamples = 10;
  
      threadMap[0] = threads.create_thread( boost::bind(&amp;process) );
      threadMap[1] = threads.create_thread( boost::bind(&amp;process) );
  
      threads.join_all();
  
      return 0;
  }
  </code></pre>