Operating Systems Reference/CPU Virtualization

Multicore, Cache Affinity & CPU Pinning

Why moving a thread between cores invalidates cache warmth, how CPU affinity and NUMA affect tail latency, and when explicit pinning helps (and when it hurts).

3/5Overview: 25m

One socket, many cores

Modern servers have dozens of cores, often grouped into NUMA nodes with local vs remote memory. The scheduler must balance load (spread work) against affinity (keep threads near warm caches). Every migration trades fairness for cache misses.

Cache hierarchy matters

L1 (per core, ~32KB) → L2 (per core) → L3 (shared) → RAM (NUMA-local vs remote)

A thread that ran on core 4 has hot L1/L2 lines there. Move it to core 37 on another socket and every memory access may pay remote NUMA latency (~2× local).

Affinity and pinning

TechniqueWhat it doesWhen to use
sched_setaffinityBind thread to CPU setLatency-sensitive, known cache footprint
NUMA-aware alloc (numactl --membind)Allocate on local nodeLarge in-memory databases
Hyperthreading awareness2 logical CPUs share one coreCPU-bound: treat as ~1.3× not 2× cores

CPU pinning helps when workload is cache-stable and migration cost exceeds load-imbalance cost. It hurts when pinned threads idle while others queue — you've disabled the scheduler's load balancer.

Hyperthreading (SMT)

Two logical CPUs share one physical core's execution units. Two CPU-bound threads on sibling hyperthreads fight for the same pipeline — throughput may be less than one thread alone. Two memory-bound threads may benefit from hiding latency.

Senior-level signal

Tail latency spikes on NUMA hosts often trace to cross-node memory or noisy neighbors on shared cores — not application logic. Check numastat, perf stat -e node-loads,node-load-misses, and whether Kubernetes placed your pod without topology spread constraints.

Where this goes next

Virtual Address Spaces begins memory virtualization — how each of those scheduled threads sees its own private memory regardless of which core it lands on.

Further Reading

Hands-On Tasks (Optional)

Low-setup exercises on your local machine. No autograding — the goal is to build intuition, not pass a test.

  • Map your machine's CPU topology

    Run `nproc` and `lscpu` (Linux) or `sysctl -n hw.ncpu hw.physicalcpu` (macOS). Note cores vs threads (hyperthreading). Understand how many truly parallel execution units you have.

    10m