Easiest way to implement shared integer counter in C++11 without mutexes: Easiest way to implement shared integer counter in C++11 without mutexes: multithreading multithreading

Easiest way to implement shared integer counter in C++11 without mutexes:


You might want to look into atomic types. You can access them without a need for a lock/mutex.


We solved a similiar problem by declaring an array[nThreads], we then gave every thread an id ranging from 0-n the thread then can write safely at its position in the array. Then you can just sum the array to get the total sum. This however is only helpful as long as you dont need to sum the array before all the threads are dead.

To be even more efficient we had a local counter at each thread which we then before the thread died appended to the array.

example (pseudo code:)

counter[nThreads];thread(int id){    // Do stuff    if(something happened)       counter[id]++;   }

or

counter[nThreads];thread(int id){    int localcounter = 0;    //Do stuff    if(something happened)       localcounter++;       //Thread is about to die    counter[id] = localcounter;}


You can use the InterlockedIncrement function.

Many functions to mutate variables in atomic ways are documented on MSDN under the banner of Synchronization Functions - they may be useful to you.