Global array storing counters updated by each thread; main thread to read counters on demand?
<p>Here's the scenario: a main thread spawns upto N worker threads that each will update a counter (say they are counting number of requests handled by each of them).</p>

<p>The total counter also needs to be read by the main thread on an API request.</p>

<p>I was thinking of designing it like so:</p>

<p>1) Global hashmap/array/linked-list of counters. </p>

<p>2) Each worker thread accesses this global structure using the thread-ID as the key, so that there's no mutex required to protect one worker thread from another.</p>

<p>3) However, here's the tough part: no example I could find online handles this: I want the main thread to be able to read and sum up all counter values on demand, say to serve an API request. I will NEED a mutex here, right?</p>

<p>So, effectively, I will need a per-worker-thread mutex that will lock the mutex before updating the global array -- given each worker thread only contends with main thread, the mutex will fail only when main thread is serving the API request.</p>

<p>The main thread: when it receives API request, it will have to lock each of the worker-thread-specific mutex one by one, read that thread's counter to get the total count.</p>

<p>Am I overcomplicating this? I don't like requiring per-worker-thread mutex in this design.</p>

<p>Thanks for any inputs. </p>

<p>Just use an <code>std::atomic&lt;int&gt;</code> to keep a running count. When any thread updates its counter it also updates the running count. When the main thread needs the count it reads the running count. The result may be less than the actual total at any given moment, but whenever things settle down, the total will be right.</p>

java python c++ multithreading pthreads