title: Safe multi-thread counter increment
body: <p>For example, I've got a some work that is computed simultaneously by multiple threads. </p>
  
  <p>For demonstration purposes the work is performed inside a while loop. In a single iteration each thread performs its own portion of the work, before the next iteration begins a counter should be incremented once.</p>
  
  <p>My problem is that the counter is updated by each thread.</p>
  
  <p>As this seems like a relatively simple thing to want to do, I presume there is a 'best practice' or common way to go about it?</p>
  
  <p>Here is some sample code to illustrate the issue and help the discussion along. 
  (Im using boost threads)</p>
  
  <pre><code>class someTask {
  public:
      int mCounter; //initialized to 0
      int mTotal; //initialized to i.e. 100000
      boost::mutex cntmutex;                
      int getCount()
      {
              boost::mutex::scoped_lock lock( cntmutex );
              return mCount;
      }
      void process( int thread_id, int numThreads )
      {
          while ( getCount() &lt; mTotal )
          {
              // The main task is performed here and is divided 
              // into sub-tasks based on the thread_id and numThreads
  
                              // Wait for all thread to get to this point
  
              cntmutex.lock();
              mCounter++;  // &lt; ---- how to ensure this is only updated once?
              cntmutex.unlock();
          }
      }
  };
  </code></pre>