Skip to content

Os Sched Cpu Affinity

DodaTech 1 min read

In this tutorial, you'll learn about How to Fix CPU Affinity Errors. We cover key concepts, practical examples, and best practices.

Fix cpu affinity errors when process migrates between CPU cores thrashing L1/L2 caches.

Quick Fix

Wrong

import os
# Default: process can run on any CPU
# OS may migrate between cores, invalidating per-core caches

Cache misses increase. L1/L2 warm data lost on migration. Performance suffers.

import os
# Get number of CPUs:
ncpus=os.cpu_count()
# Set affinity to single CPU:
os.sched_setaffinity(0, {0})  # run only on CPU 0
# Check current affinity:
cpus=os.sched_getaffinity(0)
print(f'Allowed CPUs: {cpus}')
# For thread pools:
from concurrent.futures import ThreadPoolExecutor
# Workers share same affinity as parent process
Process pinned to CPU 0. Cache warm. No migration overhead.

Prevention

Pin CPU-bound threads to specific cores. Reduce cache misses. Use sched_setaffinity.

DodaTech Tools

Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.

FAQ

What is affinity?

Process/thread bound to specific CPU cores. Prevents migration between cores.

Why pin?

Cache locality: L1/L2 cached data stays warm. No invalidation on migration.

When to use?

CPU-bound workloads, real-time threads, NUMA-aware binding.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro