What is processor affinity, and when should you control it?
Short answer: Processor (CPU) affinity is the set of CPU cores a thread is allowed to run on. By default the scheduler may move a thread to any core; pinning it to one core or a group keeps its caches warm, avoids migration costs, and isolates time-critical work from the rest of the system.
taskset -c 2 ./control_loop # run on CPU 2 only
taskset -pc 0-1 1234 # change affinity of PID 1234
#define _GNU_SOURCE
#include <sched.h>
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(2, &set);
sched_setaffinity(0, sizeof(set), &set); /* 0 = calling thread */
/* or pthread_setaffinity_np(pthread_self(), sizeof(set), &set); */
Benefits
- Cache locality: the thread's data stays in that core's L1/L2.
- Predictable latency for real-time work: combine with
isolcpus=or cpusets so no other tasks run on that core,nohz_full=to stop the scheduler tick there, and move interrupts away (/proc/irq/<n>/smp_affinity). - NUMA: keep threads near the memory they use (
numactl). - Heterogeneous CPUs: keep a heavy task on a big core, or background work on LITTLE cores.
Risks: pinning can leave cores idle while others are overloaded, because the load balancer cannot move pinned tasks. Only pin when you have measured a benefit.
Interrupt affinity is the related idea for IRQs: steer a network card's interrupts to specific cores (often matched with the threads that process the packets: RSS/RPS).
Parallel programs: for data-parallel work (OpenMP, a thread pool), pinning one worker per core avoids threads bouncing between cores; OpenMP has OMP_PROC_BIND and OMP_PLACES for this.