Home Knowledge Base Thread Affinity and CPU Pinning

Thread Affinity and CPU Pinning is the operating system and runtime technique of binding specific threads or processes to designated CPU cores — preventing the OS scheduler from migrating threads between cores, which eliminates cache migration penalties, reduces NUMA cross-socket traffic, and provides deterministic performance for latency-sensitive and throughput-critical workloads, with proper affinity configuration improving HPC and ML training performance by 10-30% on multi-socket servers.

Why Thread Affinity Matters

Setting Affinity

# Linux: Pin process to cores 0-3
taskset -c 0-3 ./my_application

# Linux: Pin to specific NUMA node
numactl --cpunodebind=0 --membind=0 ./my_application

# OpenMP: Set affinity
export OMP_PROC_BIND=close
export OMP_PLACES=cores
// Programmatic affinity (Linux)
#include <sched.h>
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(0, &cpuset);  // Pin to core 0
pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);

Affinity Strategies

StrategyBindingBest For
CompactPack threads onto fewest coresCache sharing, low-latency
ScatterSpread across all sockets/coresMemory bandwidth bound
CloseAdjacent cores, same socketBalanced locality + bandwidth
ExplicitManual core-to-thread mappingCustom tuned for specific workload

NUMA-Aware Placement

GPU Affinity

Performance Impact

ScenarioWithout AffinityWith AffinityImprovement
MPI latency benchmark2.1 µs1.4 µs33%
STREAM bandwidth180 GB/s240 GB/s33%
ML training throughput850 img/s1020 img/s20%
HPC CFD simulation45 min38 min16%

Thread affinity is the first-order performance optimization for any multi-socket server workload — while modern OS schedulers are generally good, the cache and NUMA locality benefits of explicit thread pinning are too significant to leave on the table for HPC, ML training, and latency-critical serving, making affinity configuration a standard part of production deployment tuning.

thread affinitycpu pinningprocessor affinitytasksetnuma bindingthread placement

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.