Skip to content
systemcoding.dev
Performance

The Complete Guide to Multithreaded Performance: Contention, Sharing and Scaling

Why threaded C and C++ programs stop scaling, and how to find and fix serial sections, lock contention, false sharing, bandwidth limits and bad work splits.

26 min read
Summarize in AI
Flat illustration of a rising bar chart and a gauge, with the C, C++ and Intel logos.

Adding threads to a program is easy, and getting the speed you expected from them is the hard part. A loop split across eight threads that runs three times faster, a server that gets slower when you raise the worker count, a counter that works perfectly and costs more than the work it counts: these are all the same kind of problem, and they have a short list of causes. This guide walks through that list in the order you should check it. It starts with measurement, because every later decision depends on knowing which limit you have hit. It then covers the serial fraction, lock contention, atomics, false and true sharing, work distribution, memory bandwidth, NUMA and scheduling, and finishes with a worked example that takes a shared histogram from a design that scales backwards to one that scales almost linearly. Examples are in C11 and C++17, built with gcc 13 on Linux 6.8 and x86-64, with Arm notes where the hardware differs. Code is written for the versions named and not executed here, and every output block is worked out from the code. Timings are described by their shape, not quoted, because the shape carries across machines and the numbers do not.

The guide assumes you know what a thread and a mutex are. It does not assume you know how the cache works. The posts in this series on cache lines, coherence and the cost of atomics go deeper on the hardware, and this guide links the ideas into one workflow.

What limits a threaded program

Every threaded program is limited by one of four things at any moment, and the cure for each is different.

The first is serial work. Some part of the program runs on one thread however many you have. Amdahl's law says it caps the speedup at one over the serial fraction. The cure is to shrink or overlap the serial part.

The second is contention: threads that could run in parallel wait for each other at a lock, an atomic or a shared queue. The cure is to share less, or to share more cheaply.

The third is a shared resource. Memory bandwidth, the last-level cache, the memory controller and the disk are used by all cores together, and a program that saturates one stops scaling regardless of how clean its code is. The cure is to use the resource more efficiently.

The fourth is overhead and imbalance: creating threads, splitting work into pieces too small or too uneven, and the scheduler's own costs. The cure is a better work split.

A diagnosis that does not name one of these four is a guess. The rest of the guide is how to name it.

Measure first, with a scaling curve

The most useful single measurement is a scaling curve: run a fixed workload at 1, 2, 4, 8 and more threads, and compute speedup (time at one thread divided by time at n) and efficiency (speedup divided by n). The earlier post on plotting a thread scaling curve builds the harness. The shape of the curve is the diagnosis.

ShapeTypical causeFirst check
Straight line near the idealNothing to fixCompare with ideal at the largest count
Smooth rise, flatteningSerial fraction (Amdahl)Profile the one-thread run
Peak, then declineLock or atomic contention, false sharingperf record -g, perf c2c
Plateau at low thread countMemory bandwidthInstructions per cycle, streaming test
Step at the socket boundaryNUMAnumactl, per-node allocation
Flat gain past the core countSMT siblings sharing unitsPin one thread per core

Four habits keep the curve honest. Pin threads with taskset or pthread_setaffinity_np so the scheduler does not shuffle them. Repeat each point and keep the median. Fix the CPU frequency governor to performance where you can. And warm up once, so page faults and cold caches do not land in the first measurement.

Then use the profiler to confirm. perf stat -e task-clock,context-switches,cache-misses on the largest run gives a first look: a high context-switch rate says threads are blocking, a low instructions-per-cycle figure with many cache misses says memory. perf record -g and perf report show where the time goes, and a large share in futex or a lock function is contention. perf c2c finds cache lines that several cores write. The earlier posts on measuring cache misses with perf and on context switches have the commands.

The serial fraction

Before touching threads, measure how much of the program can run in parallel at all. Profile the single-thread run and find the share of time in the code you intend to parallelise. If it is 80 percent, the ceiling is five times however many cores you throw at it. If it is 95 percent, twenty. The earlier post on Amdahl's law has the formula and a way to estimate the parallel fraction from a measured speedup.

amdahl_est.cc
#include <stdio.h>

int main(void)
{
    const double parallel[] = { 0.50, 0.80, 0.90, 0.95, 0.99 };
    for (int i = 0; i < 5; i++)
        printf("parallel %.0f%%: ceiling %5.1fx, speedup on 8 cores %.2fx\n",
               parallel[i] * 100.0,
               1.0 / (1.0 - parallel[i]),
               1.0 / ((1.0 - parallel[i]) + parallel[i] / 8.0));
    return 0;
}
Text
parallel 50%: ceiling   2.0x, speedup on 8 cores 1.78x
parallel 80%: ceiling   5.0x, speedup on 8 cores 3.33x
parallel 90%: ceiling  10.0x, speedup on 8 cores 4.71x
parallel 95%: ceiling  20.0x, speedup on 8 cores 5.93x
parallel 99%: ceiling 100.0x, speedup on 8 cores 7.48x

The table is the case for looking at the serial parts first. A program that is 90 percent parallel gets 4.7 times from eight cores at best, and a 99 percent one gets 7.5. Shaving the serial part from 10 percent to 1 percent is worth more than any amount of tuning inside the parallel loop.

What counts as serial is wider than the code you wrote single-threaded. Input parsing, output writing, a final reduction, thread start-up and join, a global lock around a shared structure and a barrier that every thread waits at are all serial in effect. Overlapping input with computation, reading the next block while processing the current one, turns a serial phase into a parallel one. Parallelising a reduction as a tree, four partial sums combined into two and then one, shortens a serial tail from n steps to log n.

Contention on locks

A mutex serialises the code it guards. If threads spend most of their time inside one critical section, the program behaves as if it were single-threaded, with extra overhead. The uncontended cost of a lock is small, one or two atomic operations. The contended cost is large: waiters sleep through the kernel, which costs context switches, and the lock's cache line travels between cores.

Four remedies, in rough order of preference.

Shorten the critical section. Do anything that need not be protected outside the lock: allocation, formatting, I/O, computation on private copies. Hold the lock only for the pointer updates or counter changes that need it. This is the cheapest fix and often enough.

Split the lock. One lock for the whole structure becomes many, each protecting a part. Lock striping, in the earlier post on fine-grained locking, maps hash buckets onto an array of mutexes, so threads using different stripes do not wait. Align the stripes to cache lines so the locks do not falsely share. Take multiple locks in a fixed order to avoid deadlock.

Replace the lock with per-thread data. If each thread can work on its own copy and merge at the end, there is nothing to lock. This is the highest-scaling answer and the one the worked example below uses.

Change the lock type. A reader-writer lock helps when reads dominate and writes are rare. A spinlock helps only for very short sections with threads pinned and no more threads than cores, as the earlier post on spinlocks and mutexes explains, because a preempted lock holder leaves spinners burning their time slices. The glibc adaptive mutex, PTHREAD_MUTEX_ADAPTIVE_NP, spins briefly then sleeps, a reasonable default when hold times vary.

A contended lock shows up in a profile as time in pthread_mutex_lock and futex calls, and in the scaling curve as a peak followed by decline: more threads, more waiters, slower. If the decline starts at two or three threads, the critical section is the whole job.

Contention on atomics

Replacing a lock with an atomic does not remove contention, only the sleeping. A shared atomic counter incremented by every thread is still a serial section: each increment needs the line in Modified state on the incrementing core, so the line moves on every operation. The earlier post on the cost of atomics goes through why an uncontended atomic is cheap and a contended one is not.

shared_atomic_hist.cc
#include <stdatomic.h>
#include <stddef.h>
#include <stdint.h>

#define BINS 256

atomic_long hist[BINS];

void count_shared(const uint8_t *data, size_t n)
{
    for (size_t i = 0; i < n; i++)
        atomic_fetch_add_explicit(&hist[data[i]], 1, memory_order_relaxed);
}

This is correct. Each thread calls it on its own slice of the data. With 256 bins of 8 bytes, the whole histogram occupies 2 KiB, 32 cache lines, and every thread updates all of them, so every line bounces among all cores. On skewed data, where a few bins are hot, the hot bins bounce constantly. The scaling curve for this code is typically flat or falling.

Two principles apply to atomics. Prefer fetch-and-add to compare-and-swap loops for counters, since a failed CAS wastes a line transfer. And remember that on x86-64 every lock-prefixed instruction is a full barrier, so a loop full of atomics also stops the processor from overlapping memory operations around them.

False sharing

False sharing is contention you did not write. Two threads update different variables that happen to sit in the same 64-byte cache line, and the coherence protocol treats it as one location, bouncing the line. The earlier posts on false sharing explain the mechanism and fix it with alignas(64) in C++ and CachePadded in Rust.

padded_slots.cppcpp
#include <atomic>
#include <cstdint>

struct alignas(64) Slot {
    std::atomic<std::uint64_t> value{0};
};

static_assert(sizeof(Slot) == 64);

Where to look for it: arrays of per-thread counters or statistics, structs with a producer-side and a consumer-side field together, arrays of small mutexes, and any loop in which different threads write adjacent elements of one array. perf c2c record then perf c2c report lists the cache lines with the most cross-core modified accesses and the offsets each thread touched, which separates false sharing (different offsets) from true sharing (the same offset). A quick test is to pad the suspect data and see whether the scaling curve straightens.

True sharing is the harder case: threads really do read and write the same variable. Padding cannot fix it. You have to change the algorithm so that threads share less, using the techniques in the next section.

Remember that 64 bytes is a convention, not a law. Apple silicon uses 128-byte lines, and some Intel cores' adjacent-line prefetcher pulls lines in pairs. Name the constant once and consider 128 where portability matters.

Share less: sharding, batching and merging

The strongest technique in this guide is to stop sharing. There are three forms.

Per-thread copies merged at the end. Each thread accumulates into private memory, and one thread, or a tree of threads, combines the results after they finish. The shared state is touched once per thread, not once per item.

Sharded structures. A counter becomes an array of padded counters, each updated by one thread or CPU and summed on read. The earlier post on sharding counters shows the code and the caveat that the sum is not an atomic snapshot.

Batching. A thread accumulates a local count and flushes it to the shared total every N operations. The shared line is touched N times less often, and the reader sees a total that lags by at most the batch size times the thread count.

All three trade memory and read cost for write scalability. They suit write-heavy, read-rarely data such as statistics, counters, histograms, accumulators and log buffers.

A worked example: the histogram

Count byte values in a large array, in parallel. The data here is deterministic so the answer is known: 1,600,000 bytes where each byte i has value i % 256, so every bin ends up with the same count.

The first design uses the shared atomic histogram above. The second gives each thread a private histogram and merges at the end.

hist_local.cc
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BINS 256
#define THREADS 4
#define N (256 * 6250)          /* 1,600,000 bytes */

struct job {
    const uint8_t *data;
    size_t begin, end;
    uint64_t local[BINS];
};

static void *worker(void *arg)
{
    struct job *j = arg;
    memset(j->local, 0, sizeof j->local);
    for (size_t i = j->begin; i < j->end; i++)
        j->local[j->data[i]]++;
    return NULL;
}

int main(void)
{
    uint8_t *data = malloc(N);
    for (size_t i = 0; i < N; i++)
        data[i] = (uint8_t)(i % 256);

    struct job jobs[THREADS];
    pthread_t th[THREADS];
    size_t chunk = N / THREADS;
    for (int t = 0; t < THREADS; t++) {
        jobs[t].data = data;
        jobs[t].begin = (size_t)t * chunk;
        jobs[t].end = (t == THREADS - 1) ? N : (size_t)(t + 1) * chunk;
        pthread_create(&th[t], NULL, worker, &jobs[t]);
    }
    for (int t = 0; t < THREADS; t++)
        pthread_join(th[t], NULL);

    uint64_t total[BINS] = { 0 };
    for (int t = 0; t < THREADS; t++)
        for (int b = 0; b < BINS; b++)
            total[b] += jobs[t].local[b];

    uint64_t sum = 0;
    for (int b = 0; b < BINS; b++)
        sum += total[b];
    printf("bin 0 = %llu, bin 255 = %llu, total = %llu\n",
           (unsigned long long)total[0], (unsigned long long)total[255],
           (unsigned long long)sum);
    free(data);
    return 0;
}
Text
bin 0 = 6250, bin 255 = 6250, total = 1600000

Each thread writes only to its own local array, 2 KiB of uint64_t, which lives inside its job struct. The job structs are 2 KiB plus a few fields, so adjacent jobs do not share a line except possibly at the very boundary between one job's last bytes and the next job's first fields, and the hot data is the middle of local. For belt and braces, add alignas(64) to the struct. The inner loop has no atomics, no barriers and no shared writes, so it runs at the speed of one thread's L1 cache, and four threads take about a quarter of the time of one, until memory bandwidth for reading data becomes the limit. The merge at the end costs THREADS * BINS additions, 1,024 here, which is nothing next to 1.6 million counted bytes.

The comparison in a scaling curve is stark. The shared atomic version gets slower as threads are added, with a decline from the second or third thread, because every update contends for the 32 lines. The local-histogram version rises almost linearly until it hits the bandwidth ceiling. The change is a few lines, and the diagnosis, from the curve and from perf c2c on the shared version, told you exactly which lines to change.

Two refinements for large histograms. If BINS is large, say a million, per-thread copies cost THREADS * BINS * 8 bytes and the merge becomes a real serial section: parallelise the merge by giving each thread a range of bins to sum across all copies. And if the data is skewed, so a few bins are hot, a local copy helps even more, since the hot bins stay in L1.

Work distribution

A correct parallel loop can still be slow because the pieces are the wrong size.

Granularity. Pieces that are too small make the overhead of handing them out comparable to the work. Pieces that are too large leave threads idle at the end, when some finish early. A rule of thumb is to create several times as many pieces as threads, large enough that each takes a few hundred microseconds or more, so scheduling cost is negligible.

Imbalance. If iteration costs vary, an even static split gives uneven finishing times and the slowest thread decides the total. Dynamic scheduling hands out the next piece to whichever thread asks. In OpenMP that is schedule(dynamic, chunk); in a hand-written pool it is a shared atomic index.

chunked.cc
#include <stdatomic.h>
#include <stddef.h>

static atomic_size_t next_chunk;

/* Returns the start of the next chunk, or n when finished. */
size_t take_chunk(size_t n, size_t chunk)
{
    size_t start = atomic_fetch_add_explicit(&next_chunk, chunk, memory_order_relaxed);
    return start < n ? start : n;
}

Each thread loops: take a chunk, process it, repeat until take_chunk returns n. The shared atomic is touched once per chunk, so with chunks of thousands of items its cost is negligible. Choose the chunk so the contended increment happens a few thousand times a second at most, not millions. Work stealing, used by Cilk, Intel TBB and Rust's rayon, takes this further with per-thread deques so threads steal from each other only when idle.

Thread count. More runnable threads than cores means time slicing, context switches and preempted lock holders. For CPU-bound work, use one thread per physical core as a starting point, and test whether SMT siblings help, which they usually do by a fraction of a core, not a whole one. For I/O-bound work, more threads than cores is reasonable, since most are blocked.

Memory bandwidth and the cache

A parallel loop that streams through a large array can saturate memory bandwidth with a few cores. After that, adding threads adds nothing, and the curve plateaus. The signature in perf stat is a low instructions-per-cycle figure that drops further as threads grow. The fix is to do more work per byte: block the computation so data is reused while it is in cache, as in the earlier post on loop tiling, fuse passes so a value is used twice per load, and shrink data types so each cache line carries more.

Private caches also matter. Threads working on disjoint data with small working sets scale well because each core's L1 and L2 serve it alone. Threads sharing a working set larger than L2 compete for the L3, which is shared. Cache partitioning, with Intel CAT through resctrl as the earlier post describes, can protect a latency-sensitive thread from a streaming neighbour.

NUMA

On a machine with more than one socket or memory domain, memory has a home node, and access from another node is slower. Linux places a page on the node of the thread that first touches it, called first-touch. A common bug is to initialise a large array on the main thread and then process it with threads on every node: all the pages sit on one node, and the threads on other nodes pay remote latency and share one node's bandwidth.

The fix is to initialise the data in parallel, with each thread touching the slice it will later process, so pages land on the right node. numactl --cpunodebind=0 --membind=0 pins a process to one node for a test, and numactl --hardware shows the topology. A step in the scaling curve at the point where threads spill onto the second socket is the classic sign.

Scheduling and affinity

The kernel moves threads between CPUs, and each move loses cache contents. Pinning a thread to a core with pthread_setaffinity_np keeps its cache warm and its prefetchers trained, at the cost of letting a busy core stall a pinned thread while another core idles. For throughput benchmarks and latency-critical threads, pinning helps. For general-purpose programs on shared machines, let the scheduler work.

SMT siblings, two hardware threads per core, share the L1, L2 and execution units. Two threads of one program on siblings can help, if each stalls on memory while the other runs, or hurt, if both want the execution units or write the same lines. And a program that shares a machine with others sees the others as noise: its scaling curve measured on a loaded machine is not the curve on an idle one.

Memory ordering

Atomic operations carry a memory order, and the strongest is not free. On x86-64, only a sequentially consistent store costs extra, a barrier that drains the store buffer. On Arm, acquire and release use dedicated instructions and relaxed accesses are plain. The earlier post on memory ordering costs has the instruction listings. In practice: relaxed for independent counters, release and acquire for publishing data from one thread to another, sequentially consistent only where a single total order is needed. A weaker order that is wrong often passes on x86 and fails on Arm, so test weak-order code on Arm.

Lock-free structures

When one producer and one consumer exchange data, a ring buffer with release and acquire atomics needs no lock and no compare-and-swap, as the post on the SPSC queue shows, and it moves items at memory speed when the producer and consumer cache each other's index. With several producers or consumers, lock-free structures need compare-and-swap on shared indices, and they inherit the contention costs of atomics: they remove blocking and not the serialisation. A lock-free queue shared by sixteen producers can be slower than sixteen producers each with its own SPSC queue merged by one consumer. Reach for lock-free code when blocking is the problem, such as in a real-time thread that must not sleep, and not as a default speed-up.

A diagnostic order

When a threaded program is slow, work through the causes in this order, since each check is cheaper than the next.

  1. Run the scaling curve and name the shape.

  2. If the curve flattens smoothly, profile one thread and find the serial fraction.

  3. If it peaks and declines, look at perf record -g for time in futex or lock functions, then at perf c2c for shared lines.

  4. If it plateaus with low instructions per cycle, test whether memory bandwidth is the limit with a streaming kernel at the same thread count.

  5. If it steps at the socket boundary, check NUMA placement.

  6. Check the work split: chunk size, imbalance, thread count against cores.

  7. Fix one thing, re-run the same harness and compare curves.

Changing several things at once makes the result unreadable.

The allocator is a shared structure too

A program can contend on a lock it never wrote. malloc and free share state between threads, and a heavily allocating loop in many threads can serialise on the allocator. glibc's allocator mitigates this with per-thread arenas, created on demand up to a limit set by M_ARENA_MAX (the MALLOC_ARENA_MAX environment variable), and a per-thread cache called tcache for small blocks, but arenas still use locks, and a block freed by a different thread than the one that allocated it goes back through the owning arena's lock. A producer that allocates messages and a consumer that frees them is the classic pattern: every free crosses arenas.

Three remedies work. Allocate less, by reusing buffers in a pool owned by one thread, or by allocating a batch up front. Allocate from per-thread arenas that you manage, such as a bump allocator reset at the end of a request. Or replace the allocator with one designed for threads: jemalloc and mimalloc both keep per-thread caches and have lower cross-thread free costs, and either can be tried without code changes by linking it or setting LD_PRELOAD. Measure the effect with the scaling curve, since an allocator swap that helps at 16 threads may do nothing at 2. A profile that shows time in malloc, free, _int_free or __lll_lock_wait_private points here.

Reductions: the pattern behind most scaling wins

Almost every parallel program ends in a reduction: many partial results become one. The shape of the reduction decides whether it is a serial tail or a scalable step. Three shapes are common.

A linear merge has the main thread add each worker's result in turn, n steps. It is trivial and fine for a few threads and a small result, and it becomes the serial tail when the result is large, as with a huge histogram.

A tree merge pairs the workers: thread 0 adds thread 1's result, thread 2 adds thread 3's, and so on, then the survivors pair again. It takes log2(n) rounds, each round running in parallel, so the tail shrinks from n steps to log2(n) steps of merging.

A range-split merge gives each thread a slice of the output, and each thread sums its slice across all the workers' partial results. Every thread does 1/n of the merging with no coordination, since slices are disjoint. This one suits large arrays.

merge_ranges.cc
#include <stddef.h>
#include <stdint.h>

/* Thread t sums output slice [lo, hi) across all workers' partial arrays. */
void merge_slice(uint64_t *out, uint64_t *const *partials, int workers,
                 size_t lo, size_t hi)
{
    for (size_t b = lo; b < hi; b++) {
        uint64_t s = 0;
        for (int w = 0; w < workers; w++)
            s += partials[w][b];
        out[b] = s;
    }
}

The inner loop reads workers values from workers different arrays at the same offset, which is cache-unfriendly for large workers, since each read is in a different array. For a handful of workers it is fine. If the output slices are laid out so adjacent threads' slices do not share a cache line, the writes to out do not falsely share. Round slice boundaries to a multiple of 8 elements of 8 bytes to be safe.

Floating-point reductions deserve a warning. Addition is not associative, so a parallel sum gives a slightly different answer than a sequential one and a different one for different thread counts, because the grouping changes. If bit-exact reproducibility matters, fix the reduction order independently of the thread count, for example by splitting the data into a fixed number of blocks and always combining the block results in the same order.

Reading a perf report for a threaded program

A concrete diagnosis makes the workflow clearer. Suppose a log-processing program with eight threads gets no faster beyond two. perf stat on the eight-thread run gives:

Text
 Performance counter stats for './logproc --threads 8':

        31,402.55 msec task-clock                #    2.41 CPUs utilized
          418,220      context-switches          #   13.3 K/sec
            5,114      cpu-migrations
      104,881,334,201      cycles
       61,442,903,118      instructions              #    0.59  insn per cycle

(These figures are illustrative.) Eight threads but only 2.41 CPUs utilised means the threads spend most of their time not running, and 418 thousand context switches in the run says they block. That points at lock contention, not bandwidth, since a bandwidth-bound program keeps its CPUs busy, waiting on memory without sleeping. Then perf record -g and perf report --no-children on the same run:

Text
Overhead  Command  Shared Object   Symbol
  38.20%  logproc  libc.so.6       [.] __lll_lock_wait
  17.65%  logproc  libc.so.6       [.] pthread_mutex_lock
  11.02%  logproc  logproc         [.] append_record
   6.30%  logproc  [kernel]        [k] futex_wait_queue

More than half the samples sit in lock-wait functions, and the callers tell you which lock: perf report -g caller shows append_record calling pthread_mutex_lock on a single global output buffer. The fix follows from the cause: give each thread its own output buffer and write the buffers out in order at the end, or use a lock-free queue to a single writer thread. After the change, the CPU utilisation climbs toward 8, the switch count collapses, and instructions per cycle rises. The three numbers, utilisation, switches and IPC, move together, which is the check that you fixed the thing the profile named, and not something nearby.

Make the curve a regression test

Scaling is easy to break and hard to notice. A change that adds a shared counter to a hot path can pass every functional test and halve the speedup at eight threads. The defence is to keep the scaling harness in the repository and run it in CI or on a schedule, on a machine with stable hardware, recording speedup at two or three thread counts. Compare against the previous result with a tolerance wide enough for noise, say ten percent, and flag a drop. Store the raw timings with the commit hash, so a regression bisects to a change.

Keep the harness honest. Run on a dedicated machine, or at least pin threads and record the CPU model and kernel version with each result, so a change in hardware is not mistaken for a code change. Report efficiency at the largest thread count as the headline, because it is the number that falls first when contention appears. And keep one benchmark that stresses the worst case, a skewed input or a hot key, since uniform data hides contention.

Choosing a parallel structure

The decision between the designs above can be reduced to a few questions about the data.

Does each thread work on its own part of the data, with results needed only at the end? Use private data and a reduction. This scales best and is the first choice.

Do threads need to share a structure during the run, with mostly reads? Use immutable data shared freely, or a reader-writer lock, or read-copy-update where the platform supports it.

Do threads share a structure with frequent writes to different parts? Split it: striped locks, per-bucket locks, or sharded structures.

Do threads share a structure with frequent writes to the same part, such as a hot counter or a single queue? There is no free answer. Batch the updates, shard the hot item, or accept that this is a serial section and size the rest of the program around it.

Does data flow from one stage to another? Use single-producer single-consumer queues between stages, one per pair, rather than one many-to-many queue.

This ordering reflects cost: private data costs nothing in coordination, and each step down adds coordination and a place for the curve to bend. The cheapest scalable design is almost always the one that avoids sharing, and the design effort is usually in finding a decomposition that does.

Thread lifetime: pools, start-up cost and wake-up latency

Creating a thread is not free. On Linux, pthread_create allocates a stack, by default 8 MiB of address space as reported by ulimit -s though only touched pages are committed, sets up thread-local storage and makes a clone system call. For a task that runs a few microseconds, creating a thread per task spends more time on the thread than on the task, and the stack and TLS setup touch memory that the new thread then reads cold. The fix is a pool: create the workers once, and hand them tasks through a queue.

A pool shifts the cost from creation to wake-up. A worker blocked on a condition variable is asleep, and handing it a task means a futex wake system call, a trip through the scheduler and a context switch onto a core, which on a busy system can take much longer than the task. Three techniques reduce the wake-up cost, each with a price.

Spinning briefly before sleeping keeps a worker on its core for a short window after finishing a task, so a task that arrives soon needs no wake-up. It burns CPU when work is sparse, so bound the spin and fall back to a sleep. Batching tasks, handing each worker many tasks in one wake-up, amortises the cost, and trades latency for throughput. And keeping the number of workers at or below the number of cores avoids a second source of delay, the scheduler placing a woken thread behind a running one.

The right choice depends on what you are optimising. A throughput job, such as a batch transform of a large file, wants few wake-ups, large tasks and one thread per core. A latency-sensitive service wants workers that are already awake, which means spinning or busy-polling on a dedicated core, and accepts the power cost. A mixed workload usually wants the middle: a pool sized to the cores, a short bounded spin and a blocking fallback.

Throughput against latency

Everything above optimised for throughput, work finished per second. Some programs care about latency, how long one request takes, and the two goals pull in different directions. A shared queue with many workers has high throughput and an unpredictable tail, because a request can sit behind a long one. Per-core queues with request affinity have lower tail latency and worse load balance. Spinning wins latency and loses efficiency. Batching wins throughput and loses latency.

State the target before tuning. If the requirement is a ninety-ninth percentile latency, measure the percentile, not the mean: a change that improves the average and worsens the tail will pass a throughput benchmark and fail in production. Record latency per request with a histogram, and look at the tail as threads and load change. Contention often hides in the tail first, because a lock that is usually free is occasionally held by a descheduled thread, and the one request that waits for it is the one in the ninety-ninth percentile.

When latency matters, shape the system to remove the sources of waiting rather than speeding up the average case. Avoid locks held across anything that can block. Avoid allocation on the hot path, or use per-thread arenas. Pin the latency-critical threads and keep other work off their cores, with isolcpus or cgroup cpusets, so the scheduler never preempts them. And keep the data they touch small and local, since a cold cache miss on a critical path costs more in a tail than in a mean.

Who this guide does not fit

If your work is I/O-bound, the limit is the device or the network, and a thread pool sized for latency hiding matters more than anything here. If your program is already single-threaded fast enough, adding threads adds bugs. If your workload runs on a GPU, the same ideas apply in different words: occupancy, coalescing and shared-memory bank conflicts replace cache lines and false sharing, and the GPU posts in this site cover them. If you use a managed runtime, Java's LongAdder and Go's per-P structures are sharded counters built into the library, and the diagnosis still starts with a scaling curve.

If you are on a language with a global interpreter lock, such as CPython before free-threaded builds, threads do not run Python code in parallel at all, and the right tool is processes or native extensions, a different problem from the ones above.

Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.