Lesson 15 of 26 · 11 min read
Lock-based concurrent data structures
Scale counters, linked lists, Michael-Scott two-lock queues, and bucketed hash tables across CPU cores without wasting time on excessive fine-grained locks.

Course syllabus · lesson 15 of 26
In this lesson
A coarse mutex gives a data structure one place to enforce its invariants. It also makes every operation wait for every other operation, even when two callers touch different data. To decide where finer locking helps, start by identifying the shared fields, the operation that changes each field, and the moment at which each change becomes visible to another caller.
Batch updates to a shared counter
Step 1 of 3
Update locally
Each CPU increments its local counter under its own lock. The shared counter can lag the exact total.
Establish a baseline before dividing the locks
Place a single lock around each operation and measure it with one thread and with the expected number of threads. Keep the amount of work fixed when asking how much faster the job finishes. Keep the amount of work per thread fixed when asking how much additional throughput more cores can handle. These experiments answer different questions. A counter can process more increments per second on four cores while still scaling far below four times the one-core rate.
Contention also has a cost when no caller goes to sleep. A frequently modified lock must move between private caches as ownership changes, and the protected data can move with it. Conversely, replacing a single mutex with many locks creates extra storage, acquisitions, and opportunities for poor locality. Compare throughput and latency under different mixes of operations. The best layout for many lookups and a few writes can differ from the best layout for a producer that rarely runs beside a consumer.
Sloppy counters and their error budget
A coarse counter has a value and a mutex. Every increment and every read takes that mutex. OSTEP's sloppy counter divides one logical total into a shared accumulator G and P local residuals, L[0] through L[P-1]. Each local residual has a lock. Frequently updating one residual lets different threads work on different cache lines, assuming good placement and a distribution that avoids sending them to the same shard. Padding can matter because two independent residuals on a single cache line can still invalidate each other's cached copies. A per-CPU design needs a reliable choice of shard, while a teaching example can use a stable thread-to-shard mapping.
Assume nonnegative unit increments, no overflow, an initial total of zero, and an integer threshold S >= 1. Each update locks its shard and increments it. On reaching S it locks the global accumulator, adds the whole local value into G, clears that residual, and releases both locks. The global read locks only the accumulator. An exact snapshot locks every shard in ascending index order, then locks the accumulator and sums it with the residuals. Taking the global lock first would conflict with the update order. Summing one shard at a time could count the same contribution first as a residual and later as part of G, or miss a flush entirely, depending on the sampling order.
After updates complete, the exact total T = G + sum(L[i]). Each residual is in the integer range from zero through S - 1, so 0 <= T - G <= P * (S - 1). The bound concerns the lag due to finished updates. An increment currently executing its flush can be treated as taking effect when the accumulator is updated. A global read returns a snapshot of G under its mutex, so comparisons with the exact total refer to the same observation time. Comparing it to an exact read taken later includes any increments that arrived in the intervening time.
If shard i receives n[i] unit increments, it flushes floor(n[i] / S) times and retains n[i] mod S. Summing those floor terms gives the total number of global acquisitions by writers. Over a long, active run, about one update in S takes the global lock, although short runs can end before some shards flush at all. Doubling S roughly halves that traffic and roughly doubles the lag bound. An allowed lag of at most E counts can be enforced by choosing S <= floor(E / P) + 1. The calculation is a worst-case bound even if some shards see little work. If updates can be negative, this one-sided policy and bound no longer apply without additional rules for flushing negative residuals.
If the counter exports telemetry, an old but bounded count may be acceptable. If it enforces an allocation limit, a global read that lags finished allocations cannot safely authorize more allocations on its own. Even an exact count requires an atomic check-and-reserve step to enforce the limit against simultaneous callers. Decide what the read means before choosing an approximation threshold.
typedef struct counter_t {
int global; // shared global sum
pthread_mutex_t glock; // global lock (order: shard lock -> glock)
int local[NUMCPUS]; // per-CPU residual counters
pthread_mutex_t llock[NUMCPUS]; // one mutex per shard
int threshold; // flush threshold S
} counter_t;
void counter_update(counter_t *c, int thread_id, int amt) {
int cpu = thread_id % NUMCPUS;
pthread_mutex_lock(&c->llock[cpu]);
c->local[cpu] += amt;
if (c->local[cpu] >= c->threshold) {
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]);
}
int counter_get(counter_t *c) {
pthread_mutex_lock(&c->glock);
int val = c->global;
pthread_mutex_unlock(&c->glock);
return val; // approximate total within P * (S - 1) for unit updates
}
Lists, publication, and node lifetime
For a singly linked list, the head pointer and the reachable links constitute the shared structure. A push can allocate a node and fill its payload before acquiring the list mutex. Under the lock it sets the new node's next pointer to the current head and publishes the new head. That publication is where the push takes effect. Preparing the private node first shortens the critical section and places the allocation failure before any lock acquisition.
A membership lookup under the same list mutex can walk the links and return a copied result. Returning a raw pointer changes the contract: if callers can delete nodes, the next thread to acquire the lock could free the returned node while the first caller still uses it. Either keep use within the lock, transfer ownership, or provide a separate lifetime scheme. A lock around lookup by itself protects only the traversal.
Hand-over-hand locking gives each node a mutex. During traversal, take the successor's mutex before releasing the current node's. The predecessor lock protects the link during the transition. Any deletion algorithm has to respect the same traversal and lifetime rules, including the case where a thread is about to acquire a node's mutex. This allows operations in different parts of the list to overlap, but a traversal of a thousand links still incurs on the order of a thousand acquisitions. If all operations start at the head or list searches dominate, node locks can be more expensive than the coarse lock they replaced.
The Michael–Scott two-lock queue
The queue has a head pointer and a tail pointer, each with its own mutex. Each node has a payload and a next link. The head points to a dummy node whose payload is ignored. The logical queue consists of the nodes after the dummy. In an empty queue, head and tail refer to the same node and the dummy's next link is null.
An enqueue allocates and initializes a node before acquiring the tail lock. Under that lock, it appends the node by publishing a link from the old tail, then advances the tail pointer. The link publication makes the insertion visible to a dequeuer. A dequeue takes the head lock and reads the dummy's next link. If it sees null, it reports empty at that observation point. Otherwise it copies the successor's payload and makes the successor the new dummy. It can reclaim the old dummy after dropping the head lock once its own access to the dummy is complete. A dequeue takes effect when it advances the head under that lock.
The head and tail locks serialize operations at each end. The next link can still be shared between the ends, especially when both pointers refer to the dummy. In a modern C implementation use an atomic link. For example, the producer initializes the payload and performs a release store of the newly linked pointer. A consumer's acquire load of that pointer makes the initialized payload visible. A head mutex acquired by the consumer cannot by itself synchronize with a different tail mutex held by the producer. The producer must finish all accesses to the old tail node by the time it publishes the link, since a dequeuer may immediately retire that node. Advancing the private-to-producers tail pointer under its lock does not require accessing the old node again.
One enqueue and one dequeue can run concurrently, but two producers still share the tail lock and two consumers still share the head lock. This is a blocking lock-based algorithm, and a dequeue that reports empty returns immediately. Waiting for a new item or for capacity in a bounded queue requires a separate condition or semaphore protocol.
The dummy also keeps the consumer from having to reset the tail when it removes the last item. After removing that item, head already names the node from which the next producer can append. In a design that instead represented emptiness with two null pointers, the empty-to-nonempty transition would need to establish both endpoints, and removing the last item would have to coordinate with producers to clear both safely.
Hash tables and bucket ownership
A fixed-size hash table can use one lock for each bucket. Hash the key, choose its bucket, and operate on that bucket's chain under its lock. Operations on two keys can overlap when the keys land in different buckets. Conversely, a frequently accessed key always lands in the same bucket. Adding buckets reduces collisions for well-distributed distinct keys and does little for a workload dominated by one key.
For B buckets and two independent uniform choices, the probability of choosing the same bucket is 1 / B. That calculation does not predict the contention of a skewed workload. If bucket i has access probability p[i], independent choices collide with probability sum(p[i] * p[i]). A resize involves changing the mapping itself, so protecting each old chain independently is insufficient. A design needs a mechanism that coordinates array publication and keeps old buckets alive while current operations still use them.
Worked trace
Set P = 4 and S = 5. Suppose the four shards receive four, four, nine, and four increments, respectively. The third shard flushes once on its fifth update, then accumulates four more. At the end G = 5, the residuals are all four, and T = 21. The lag is sixteen, precisely 4 * (5 - 1). One global acquisition by writers has served twenty-one increments. The next update on any shard moves five into G while increasing T by just one. The lag drops from sixteen to twelve.
For the queue, start with dummy D and enqueue A. The producer links D.next to A and is paused before advancing the tail pointer. The consumer sees A under its head lock, copies A's payload, and makes A the dummy. It can reclaim D because the producer finished accessing D when it published the link. The producer resumes and sets tail to A before releasing the tail lock. The next producer can safely append to A. The logical queue is empty even though, for a short interval, the tail field had yet to catch up with the link publication.
Change one input
Keep the same four update totals and reduce the counter threshold from five to two. The shards flush two, two, four, and two times, for ten acquisitions by writers. Now G = 20, with residuals of zero, zero, one, and zero. The exact total remains twenty-one and the current lag is one. The new worst-case bound is four. This quantifies what was bought with the extra global lock acquisitions. The next lesson adds blocking waits for state changes to structures such as bounded queues.
Before you move on
Try it in your workspace
Trace a sloppy (approximate) counter with threshold S=1024 across four CPU cores, then trace a hand-over-hand list or Michael-Scott two-lock queue to see where contention moves.
Keep a short note of what you tried, what passed, and what you still need to check.
0 of 3 checked.
Saved in this browser when storage is available. Uncheck any item to revisit it. This is your own record, not an assessment.