Concurrent Counters
This lesson explains how to make a simple data structure like a counter thread safe while ensuring good performance.
We'll cover the following
One of the simplest data structures is a counter. It is a structure that is commonly used and has a simple interface. We define a simple non-concurrent counter in the code excerpt below.
typedef struct __counter_t {int value;} counter_t;void init(counter_t *c) {c->value = 0;}void increment(counter_t *c) {c->value++;}void decrement(counter_t *c) {c->value--;}int get(counter_t *c) {return c->value;}
Simple but not scalable
As you can see, the non-synchronized counter is a trivial data structure, requiring a tiny amount of code to implement. We now have our next challenge: how can we make this code thread safe? The code excerpt below shows how we do so.
typedef struct __counter_t {int value;pthread_mutex_t lock;} counter_t;void init(counter_t *c) {c->value = 0;Pthread_mutex_init(&c->lock, NULL);}void increment(counter_t *c) {Pthread_mutex_lock(&c->lock);c->value++;Pthread_mutex_unlock(&c->lock);}void decrement(counter_t *c) {Pthread_mutex_lock(&c->lock);c->value--;Pthread_mutex_unlock(&c->lock);}int get(counter_t *c) {Pthread_mutex_lock(&c->lock);int rc = c->value;Pthread_mutex_unlock(&c->lock);return rc;}
This concurrent counter is simple and works correctly. In fact, it follows a design pattern common to the simplest and most basic concurrent data structures: it simply adds a single lock, which is acquired when calling a routine that manipulates the data structure, and is released when returning from the call. In this manner, it is similar to
At this point, you have a working concurrent data structure. The problem you might have is performance. If your data structure is too slow, you’ll have to do more than just add a single lock; such optimizations, if needed, are thus the topic of the rest of the chapter. Note that if the data structure is not too slow, you are done! No need to do something fancy if something simple will work.
To understand the performance costs of the simple approach, we run a benchmark in which each thread updates a single shared counter a fixed number of times; we then vary the number of threads. The graph below shows the total time taken, with one to four threads active; each thread updates the counter one million times. This experiment was run upon an iMac with four Intel 2.7 GHz i5 CPUs; with more CPUs active, we hope to get more total work done per unit time.
From the top line in the figure (labeled ’Precise’), you can see that the performance of the synchronized counter scales poorly. Whereas a single thread can complete the million counter updates in a tiny amount of time (roughly 0.03 seconds), having two threads each update the counter one million times concurrently leads to a massive slowdown (taking over 5 seconds!). It only gets worse with more threads.
Ideally, you’d like to see the threads complete just as quickly on multiple processors as the single thread does on one. Achieving this end is called perfect scaling; even though more work is done, it is done in parallel, and hence the time taken to complete the task is not increased.
Scalable counting
Amazingly,
Many techniques have been developed to attack this problem. We’ll describe one approach known as an
The approximate counter works by representing a single logical counter via numerous local physical counters, one per CPU core, as well as a single global counter. Specifically, on a machine with four CPUs, there are four local counters and one global one. In addition to these counters, there are also locks: one for each local counter1, and one for the global counter.
The basic idea of approximate counting is as follows. When a thread running on a given core wishes to increment the counter, it increments its local counter; access to this local counter is synchronized via the corresponding local lock. Because each CPU has its own local counter, threads across CPUs can update local counters without contention, and thus updates to the counter are scalable.
However, to keep the global counter up to date (in case a thread wishes to read its value), the local values are periodically transferred to the global counter, by acquiring the global lock and incrementing it by the local counter’s value; the local counter is then reset to zero.
How often this local-to-global transfer occurs is determined by a threshold . The smaller is, the more the counter behaves like the non-scalable counter above; the bigger is, the more scalable the counter, but the further off the global value might be from the actual count. One could simply acquire all the local locks and the global lock (in a specified order, to avoid deadlock) to get an exact value, but that is not scalable.
To make this clear, let’s look at an example (in the figure below).
In this example, the threshold is set to 5, and there are threads on each of four CPUs updating their local counters . The global counter value () is also shown in the trace, with time increasing downward. At each time step, a local counter may be incremented; if the local value reaches the threshold , the local value is transferred to the global counter and the local counter is reset.
The lower line in the graph shown earlier (labeled ’Approximate’) shows the performance of approximate counters with a threshold of 1024. Performance is excellent; the time taken to update the counter four million times on four processors is hardly higher than the time taken to update it one million times on one processor.
The graph below shows the importance of the threshold value , with four threads each incrementing the counter 1 million times on four CPUs. If is low, performance is poor (but the global count is always quite accurate); if is high, performance is excellent, but the global count lags (by at most the number of CPUs multiplied by ). This accuracy/performance trade-off is what approximate counters enable.
A rough version of an approximate counter is found in the code excerpt below. Read it, or better yet, experiment yourself to better understand how it works.
typedef struct __counter_t {int global; // global countpthread_mutex_t glock; // global lockint local[NUMCPUS]; // per-CPU countpthread_mutex_t llock[NUMCPUS]; // ... and locksint threshold; // update frequency} counter_t;// init: record threshold, init locks, init values// of all local counts and global countvoid init(counter_t *c, int threshold) {c->threshold = threshold;c->global = 0;pthread_mutex_init(&c->glock, NULL);int i;for (i = 0;i < NUMCPUS; i++){c->local[i] = 0;pthread_mutex_init(&c->llock[i], NULL);}}// update: usually, just grab local lock and update// local amount; once local count has risen ’threshold’,// grab global lock and transfer local values to itvoid update(counter_t *c, int threadID, int amt) {int cpu = threadID % NUMCPUS;pthread_mutex_lock(&c->llock[cpu]);c->local[cpu] += amt;if (c->local[cpu] >= c->threshold) {// transfer to global (assumes amt>0)pthread_mutex_lock(&c->glock);c->global += c->local[cpu];pthread_mutex_unlock(&c->glock);c->local[cpu] = 0;}pthread_mutex_unlock(&c->llock[cpu]);}// get: just return global amount (approximate)int get(counter_t *c) {pthread_mutex_lock(&c->glock);int val = c->global;pthread_mutex_unlock(&c->glock);return val; // only approximate!}
TIP: MORE CONCURRENCY ISN’T NECESSARILY FASTER
If the scheme you design adds a lot of overhead (for example, by acquiring and releasing locks frequently, instead of once), the fact that it is more concurrent may not be important. Simple schemes tend to work well, especially if they use costly routines rarely. Adding more locks and complexity can be your downfall. All of that said, there is one way to really know: build both alternatives (simple but less concurrent, and complex but more concurrent) and measure how they do. In the end, you can’t cheat on performance; your idea is either faster, or it isn’t.
Get hands-on with 1400+ tech skills courses.