Threads share one address space, so every shared update needs an atomic instruction that orders it, and a wait should cost nothing until it is real: an uncontended lock is one atomic instruction (about 10 ns), and only a thread that truly has to wait asks the kernel to put it to sleep, on a futex when it waits for another thread, on epoll or io_uring when it waits for I/O.
Every wait on Linux ends in one of two kernel queues. The figure plays both, with the costs measured here (sections 3, 4, 8):
w from 0 to 1 with one compare-and-swap: 10.1 ns for a pthread_mutex_t here, no system call.w taken, set it to 2 ("someone waits") and call futex_wait(w, 2): the kernel checks that w is still 2 and puts them in the futex queue for w. Asleep, they use no CPU.futex_wake(w, 1): B leaves the queue and runs again, 1.7 µs later on the same CPU, 23.5 µs across CPUs in this VM.epoll_ctl ADD); the kernel keeps them in an interest list, and the loop's one thread sleeps in epoll_wait.epoll_wait returns just that one: 352 ns per wait with 10,000 sockets watched, where poll pays 650 µs to check them all.In the root's training job (section 10), the main thread, PyTorch's OpenMP pool and the queue feeder threads sleep on futexes; the DataLoader workers sleep in poll.
You need: what a process, a system call and a file descriptor are (Processes and the system-call API) and what a context switch and a time slice are (Scheduling and CPU time). Language-level async (asyncio's API, the JavaScript event loop's phases) is on the programming-languages pages; database concurrency control on Transactions and concurrency; GPU streams on Streams, CUDA graphs and multi-GPU programming.
The running example is the training job of the root page (a CPU-only PyTorch run with a memory-mapped dataset and two DataLoader workers). Seen as threads, while it trains (measured in section 10):
| Mechanism | The problem it solves | Cost measured here | Where it bites in ML work | See it with |
|---|---|---|---|---|
| Thread | Several flows of control sharing one address space | create + join 136.0 µs in this VM; 8 MiB of address space each, almost none of it touched | Thread pools sized from the machine, not the container | ls /proc/<pid>/task, top -H |
| Atomic instruction | A read-modify-write no other core can split | 8.3 ns per update, uncontended | Reference counts, counters, lock words | the assembly (ldadd, ldaxr/stlxr) |
| Lock (mutex) | Only one thread at a time in a critical section | 10.1 ns uncontended; a spinlock wastes whole time slices when the holder is preempted | Logging, metrics, allocator and queue locks under many threads | perf lock, strace -f -e futex |
| Futex | Sleep in the kernel only when a lock is really taken | 0 system calls uncontended; a wake-up costs 1.7 µs on one CPU, 23.5 µs across CPUs in this VM | Every PyTorch, NCCL and Python lock and queue | /proc/<pid>/task/*/wchan |
| Condition variable, semaphore | Sleep until something is true ("a batch is ready") | Mesa semantics: woken is not "true"; one shared condition variable hangs | Producer/consumer queues in loaders and servers | py-spy, gdb |
| Deadlock | A cycle of threads each waiting for the next | Hangs forever at 0% CPU | Fork with a held lock; lock-order bugs in callbacks | py-spy dump, wchan |
| GIL | CPython's one lock for all Python bytecode | An I/O thread wakes 8.0 ms late next to one busy Python thread | Latency of a data or serving thread next to Python work | sys.getswitchinterval(), py-spy |
| epoll, io_uring | One thread waiting on thousands of connections or I/Os | poll on 10,000 descriptors 650 µs per call, epoll_wait 352 ns | Async model servers, data streaming clients, asyncio | strace -e epoll_pwait |
All numbers on this page were measured in Docker Desktop's Linux VM on an Apple M1 Pro (Linux 5.10.104, arm64, 5 CPUs, glibc 2.36, Python 3.11.2, torch 2.14.1 CPU), 2026-10-05, with other experiments sharing the VM: measured here marks them, from source marks what is read from code at a pinned tag, not run here marks what needs a GPU or a newer kernel. Raw outputs are in the page's src/runs/out/. Sections 1 to 6 follow OSTEP's concurrency chapters (26 to 32) and add the Linux interfaces; the reading map is in the depth section.
ch. 26 Concurrency: an introduction, ch. 27 Thread API
A process (owned by Processes and the system-call API) has one flow of control: one program counter and one stack. To use several cores on one shared data structure, a program needs several flows of control that see the same memory. That is a thread: its own registers, program counter and stack; everything else (heap, globals, open files, signal handlers) shared with the other threads of its process. Concurrency is several activities in progress at once; parallelism is some of them running at the same instant on different cores.
How Linux makes one. The kernel has no separate thread object: a thread is a task (a task_struct, the kernel's schedulable unit) created with flags that make it share its parent's memory and tables. pthread_create in glibc 2.36 asks for exactly this sharing (nptl/pthread_create.c L277-281); strace shows the recipe measured here:
getpid(), a new thread id (gettid())tpidr_el0 on arm64, fs on x86-64) at this thread's thread-local storagepthread_join learns it endedulimit -s = 8192 KiB) of address space, not memory: 2,000 idle threads in section 8 reserved 18683 MiB of virtual memory but added only 13 MiB of resident memory, because untouched stack pages are never allocated (demand paging: Virtual memory). On Linux threads and processes are both tasks, so a container's pids.max counts threads too (the root's Debug lab, "BlockingIOError on fork: the pids limit counts threads too").What clone's flags (left) share, and what each thread keeps for itself.
Before the clone, glibc maps the stack plus a guard region mapped PROT_NONE, so that a stack overflow faults instead of silently overwriting a neighbour. The guard is 64 KiB here although pthread_attr_getguardsize reports 4096 bytes: glibc rounds it up to the architecture minimum on arm64 (sysdeps/aarch64/nptl/pthreaddef.h L23, nptl/allocatestack.c L345-346). Newer glibc versions try clone3 first and fall back to clone (clone-internal.c L52-55); glibc 2.36 on arm64 has no clone3 wrapper, so the trace shows plain clone.
Thread-local storage (TLS) is a variable declared __thread (C) or thread_local (C++): one copy per thread, found through the thread pointer. errno is one, which is why two threads can make failing system calls at once without overwriting each other's error code. The same program printed its variables' addresses from three threads:
Thread 0 is the main thread. The shared global has one address; tls_var and the stack differ between the main thread and the others. Threads 1 and 2 print the same addresses because the program joins thread 1 before creating thread 2, and glibc reuses the cached stack and TLS block.
exit() from any thread ends the whole process. exit calls exit_group, which ends every thread in the thread group; to end only the calling thread, return from its function or call pthread_exit. The same holds for a signal whose default action is to terminate: it kills the whole process, whichever thread it was delivered to.
ch. 26.3 to 26.5, ch. 28.6 to 28.11
When two threads update the same memory and nothing orders them, the result depends on timing: a race condition. Two unordered accesses to one location, at least one a write, are a data race; in C, C++ and Rust's unsafe code that is undefined behaviour, not merely a wrong number. The classic one, count = count + 1 on two threads, is three instructions (load, add, store). Predict the final count after two increments from 41, then watch the two threads as lanes in time, with the shared counter between them:
count = count + 1: load into a register, add 1, store back. The values are illustrative.m.m with one compare-and-swap; T2 finds it taken and parks in the kernel on m's futex (section 4).count.futex_wake; T2 takes m.ldadd on arm64, lock xadd on x86-64).The root page measured the same race at full speed (two threads, 10 million increments each, about half lost) and its OS simulators tab runs OSTEP's x86.py programs. A concurrency bug needs a particular order of steps, which is why it passes tests and fails in production. Code that touches shared data and must not run in two threads at once is a critical section.
Atomic instructions are the hardware fix: one read-modify-write of one word as one indivisible step. Three families matter:
old = *p; *p = old + v in one step. arm64 v8.1 has ldadd; x86-64 has lock xadd. Counters and reference counts.old = *p; *p = v. The simplest lock: while (xchg(&l, 1) == 1) ;*p == expected then *p = new, and say whether it did. Everything lock-free is built on it. arm64 v8.1 cas; x86-64 lock cmpxchg.An atomic update is not free: on one thread it cost 8.3 ns here against well under a nanosecond for a plain add, and with four threads updating one counter the cache line holding it bounces between cores (C++: the machine underneath, section 8 measures false sharing and shows the same effect for neighbouring variables).
Memory order. Cores also do not make their writes visible to each other in program order: each core puts stores in a private store buffer and lets later loads run ahead of them. x86-64 allows only that one reordering (a later load passing an earlier store); arm64 allows more. C++: the machine underneath, section 8 measures the message-passing reordering on this chip and explains acquire, release and sequentially consistent orders; here is what it does to a lock. Peterson's algorithm (OSTEP 28.6) is a correct two-thread lock using only loads and stores, proved in 1981 on the assumption that memory is sequentially consistent:
void lock(int me) { int other = 1 - me; flag[me] = 1; // I want in turn = other; // but you go first if you also want in while (flag[other] && turn == other) ; // wait while you want in and it is your turn } void unlock(int me) { flag[me] = 0; }
If the store flag[me] = 1 is still in this core's store buffer when the load flag[other] runs, both threads read the other's flag as 0 and both enter. Two threads, each entering 20 million times, with a non-atomic count = count + 1 inside measured here (src/runs/c/peterson.c):
The fix is to declare the order you need: with sequentially consistent atomics the compiler emits the ordering instructions (stlr and ldar on arm64, or a full barrier dmb ish) and the lock is correct. Real locks never rely on plain loads and stores; they use an atomic exchange or CAS, which carry the ordering with them (acquire on lock, release on unlock). volatile is not a fix: it only stops the compiler from removing or merging accesses; the load, add and store stay three steps, unordered across cores (the root's race measurement used a volatile counter).
Load-linked / store-conditional is the older arm64 form (ldaxr then stlxr): the store fails if anyone wrote the word in between, and the code loops. GCC's "outline atomics" pick LSE or LL/SC at run time (the root's assembly shows a call to __aarch64_ldadd8_acq_rel).
A lock-free data structure guarantees that some thread always makes progress, even if others are paused at any instruction, because nobody ever holds a lock. The building block is a CAS loop: read the current value, compute the new one, and CAS it in; if another thread changed it meanwhile, the CAS fails and you retry. A stack push:
do { n->next = head; } while (!CAS(&head, n->next, n));
The traps: the ABA problem (the head was A, became B, became A again; the CAS succeeds although the list changed underneath; fixed with version counters or safe memory reclamation), and freeing memory another thread may still be reading (fixed by hazard pointers, epochs, or RCU, read-copy-update, which the Linux kernel uses so that readers take no lock at all: What is RCU). The common, safe case in practice is a single-producer single-consumer ring buffer: one thread only advances the tail, the other only the head, and each reads the other's index with acquire order. io_uring's two rings (section 8) are exactly that, shared between a program and the kernel. Use lock-free structures from a library (C++: the machine underneath's atomics, Rust's crossbeam, std::atomic counters); a lock is usually fast enough (section 3: 10 ns uncontended) and far easier to get right.
ch. 28 Locks, ch. 29 Lock-based concurrent data structures
A lock (or mutex) is a word in memory plus two operations: lock() returns only when the caller owns it, unlock() gives it up. OSTEP judges a lock on correctness (mutual exclusion), fairness (can a waiter starve?) and performance (uncontended, contended on many CPUs, contended on one CPU). The design question is what a thread does when the lock is taken:
sched_yield() after each failure (OSTEP 28.13): a system call per failed attempt, and no promise about who runs next.PTHREAD_MUTEX_ADAPTIVE_NP spins at most 100 rounds by default, with exponential backoff (nptl/pthread_mutex_lock.c L139-158; tunable glibc.pthread.mutex_spin_count).pthread_mutex_t), because it never enters the kernel. A lock that makes a system call on every unlock costs 288.6 ns: about thirty times more, for nothing.Rule: never spin in user space unless every thread has its own CPU (pinned threads in a low-latency system). The Linux kernel spins because kernel code can disable preemption while holding a spinlock; user space sleeps.
Seven ways to protect one shared counter in four situations measured here (src/runs/c/locks.c; "work" is a loop of about 0.3 ns per iteration; median of 3 runs). Predict which design wins with four threads on one CPU, then pick that situation.
ch. 28.14 to 28.16 (Linux futex, two-phase locks) from source measured here
Sleeping needs the kernel, but entering it costs about 300 ns, thirty times an uncontended lock. The futex ("fast user-space mutex", Linux 2.6, 2003) splits the job: the lock word lives in ordinary user memory and is changed with atomic instructions; the kernel is asked only to sleep on that word or to wake sleepers on it (futex(2); Drepper, Futexes Are Tricky, 2011). Two operations do almost all the work:
*addr still equals val, put me to sleep on addr; otherwise return at once with EAGAIN". The comparison and the going to sleep happen together inside the kernel, under a lock no waker can slip past.n threads sleeping on addr". It does not change *addr; the user-space code changed it already.glibc's mutex protocol uses three values for the lock word: 0 free, 1 locked with nobody waiting, 2 locked and someone may be waiting. Simplified from sysdeps/nptl/lowlevellock.h L94-106 and L145-160 and nptl/lowlevellock.c L38-50:
void lock(int *w) { if (CAS(w, 0, 1)) return; // fast path: free, now mine, no system call if (*w == 2) goto wait; while (xchg(w, 2) != 0) // mark "waiters"; if it was 0 I own it now (as 2) wait: futex_wait(w, 2); // sleep, but only if it is still 2 } void unlock(int *w) { if (xchg(w, 0) > 1) // was 2: someone may be asleep futex_wake(w, 1); // wake one; it retries the xchg }
Play the protocol with three threads on one lock word:
w = 0 and swaps in 1. No system call: 9.2 ns for the hand-built futex lock here, 10.1 ns for pthread_mutex_t.xchg(w, 2) returns 1, not 0, so B does not own the lock, but w now says "someone may be waiting".w's address, reads w, finds it still 2, and queues B. B is off the CPU.w = 2 and goes straight to futex_wait(w, 2). Two sleepers; the word in user memory is all that records them.xchg(w, 2) returns 0: B owns the lock, and leaves it at 2 because it cannot know whether C is still asleep.Uncontended, lock is one CAS and unlock one exchange: no system call. The hand-built version in locks.c counts its own system calls: with four threads and short critical sections it made 208840 futex waits in 2 million acquisitions (about one acquisition in ten had to sleep).
Why not check the word in user space and then call a plain "sleep"? Because between the check and the sleep the holder can unlock and send its wake-up to a thread that is not asleep yet; the wake-up is lost and the waiter sleeps forever. The kernel source states the rule (kernel/futex.c L2633-2648, v5.10): "The basic logical guarantee of a futex is that it blocks ONLY if cond(var) is known to be true at the time of blocking". So futex_wait_setup locks the wait queue first, then reads *uaddr, and returns EAGAIN if it changed (L2650-2678). Be the scheduler and produce it yourself:
Press a thread's button to run its next indivisible step. In "check, then sleep", 54 of its 376 possible schedules leave a thread asleep forever; the futex version has none.
How this is checked: the page explores every interleaving in your browser (a depth-first search over states, counting the distinct schedules that lead to each ending); src/recompute.py does the same search with an independent Python implementation of the same programs (src/inputs/lab_programs.json), and the pill says whether the two agree.
Threads A and B each need the lock twice (a 2 µs critical section, 1 µs of other work between), while thread C has 8 µs of unrelated work and no lock, all on 2 CPUs. Costs are this VM's measured ones: a futex system call 0.3 µs (the "wake on every unlock" lock's 288.6 ns per pair), and a wake-up of 1.7 µs (same CPU) or 23.5 µs (across CPUs in this VM), half a ping-pong round trip. The time slice is shortened to 3 µs so that preemption shows at this scale illustrative slice. Predict which design lets C finish first, then pick it: the timeline opens on the finished run, and play or the scrubber replays it event by event.
Switch to the cross-CPU wake-up: the futex's hand-offs become far slower than spinning, which is why glibc offers an adaptive mutex and why the kernel and NCCL spin when they expect the wait to be short.
What a wake-up costs. Two threads passing a turn back and forth 200,000 times measured here (pingpong.c; round trip = two hand-offs; median of 5):
On one CPU a hand-off is a context switch: 1.7 µs, in line with the root's 1.33 µs pipe ping-pong. Across CPUs the idle CPU must be woken by an inter-processor interrupt, which a virtual machine turns into a trip through the hypervisor (Virtualization and the GPU driver stack, section 5); bare metal not run here. Spinning across two CPUs never sleeps (0.09 µs per round trip), but on one CPU each spin waits for a whole time slice: 19.8 ms per round trip, about 220,000 times slower.
threading.Lock and queue.Queue, PyTorch's thread pools, libgomp's barriers and NCCL's idle proxy thread all sleep on futexes, so in a hung process cat /proc/<pid>/task/*/wchan shows futex_wait_queue_me (5.10; futex_wait_queue on 6.x) for nearly every thread. Thousands of futex(..., FUTEX_WAIT_PRIVATE, 2, NULL) = -1 EAGAIN lines under strace are not a bug: the word changed before the kernel compared, and the caller retries (about a fifth of the job's futex calls in section 10 return an error; strace -c does not name it, and for these waits the usual ones are EAGAIN and, for timed waits, ETIMEDOUT).The kernel does not allocate anything per futex while nobody waits. Sleepers go into one global hash table of wait queues, indexed by a key for the address: for a private futex (threads of one process; glibc passes FUTEX_PRIVATE_FLAG) the key is the address space and the virtual address; for a shared futex (a lock in memory mapped by several processes) it is the underlying page and offset, so different virtual addresses in different processes meet in the same queue (get_futex_key, kernel/futex.c L487-653). The table has roundup_pow_of_two(256 × CPUs) buckets (L4050), 2,048 on this 5-CPU VM. The full comment: "If we locked the hash-bucket after testing *uaddr, that would open a race condition where we could block indefinitely with cond(var) false, which would violate the guarantee." Python's multiprocessing.Lock is a POSIX semaphore in a /dev/shm/sem.* file mapped by both processes, so its futex is shared: no _PRIVATE in the trace measured here:
FUTEX_CLOCK_REALTIME: a wait with an absolute deadline; glibc uses it for timed waits and POSIX semaphores (the trace above).EOWNERDEAD), for locks in memory shared between processes.ch. 30 Condition variables, ch. 31 Semaphores
A lock says "one at a time"; it cannot say "wait until a batch is ready" or "until there is room in the queue". A condition variable is a queue of sleeping threads attached to a condition the program tracks in its own variables, always used with a mutex: wait(cv, m) atomically releases m and sleeps, and re-takes m before returning; signal(cv) wakes one sleeper, broadcast(cv) all. The atomic "release and sleep" is section 4's lost-wake-up problem, solved the same way (glibc builds it on futexes).
Rule 1: re-check the condition in a while loop. POSIX and Linux use Mesa semantics: a woken thread is only told the condition was true at some moment; another thread may have run in between and made it false again (and implementations may wake a thread spuriously). OSTEP's producer/consumer with one slot, one producer and two consumers, 200,000 items measured here (condvar.c, three runs of each version; raw output in the closed block below). With if, a consumer woke up to an empty slot 45 to 88 times per run: in real code, reading garbage or an exception from an empty queue, rarely enough to pass every test. With while, the same situations happen (37 to 70 re-checks per run) and are harmless. The lab in section 4 counts every schedule of a two-item version: with if, 64,228 of 42,827,788 schedules make a consumer read an empty slot; with while, none of 91,732,872 do. Open the "if" scenario in the lab and let C2 barge in between P's signal and C1's return.
Rule 2: one condition variable per condition. With one variable shared by "slot full" and "slot empty", a consumer's signal can wake the other consumer instead of the producer; then all three sleep and the program hangs at 0% CPU. It hung in 3 of 3 runs, after a handful of items. Use two condition variables (or broadcast, which is correct but wakes everyone). NCCL's proxy thread follows rule 1 with a predicate lambda: "Predicate avoids lost wakeups and guarantees we observe stop after ncclProxyProgressDestroy" (src/proxy.cc L849-851, NCCL v2.32.3-1).
A semaphore (Dijkstra, 1960s) is a counter: wait (P, down) decrements it and sleeps while it would go below zero; post (V, up) increments it and wakes a sleeper. Initialised to 1 it is a lock; to N it admits at most N holders ("at most 2 prefetched batches per worker", the DataLoader's prefetch_factor, is this idea); to 0 it is a "wait until done" signal. POSIX sem_t is a futex word; multiprocessing's locks, semaphores and queues are sem_t in /dev/shm. Unlike a mutex, any thread can post a semaphore: nothing records an owner, which makes it easy to misuse.
A barrier makes N threads wait until all N arrive. OpenMP puts one at the end of every parallel region, which is where PyTorch's math threads sit between operators: libgomp spins at the barrier for a while (do_spin in libgomp/config/linux/wait.h; tuned by GOMP_SPINCOUNT and OMP_WAIT_POLICY) and then sleeps on a futex; section 10's gdb snapshots find the pool threads in futex_wait inside gomp_barrier_wait_end.
A reader-writer lock lets many readers in at once or one writer alone; good for data read far more than written (a model registry, a config). The catch is starvation: glibc's pthread_rwlock_t prefers readers by default, so a steady stream of readers can keep a writer waiting indefinitely (PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP changes it; pthread_rwlockattr_setkind_np(3)). For short critical sections an rwlock is often slower than a mutex, since even readers write the shared reader count.
ch. 32 Common concurrency problems
A deadlock is a set of threads each waiting for something another member holds, so none can move. It needs four conditions at once (Coffman, 1971): mutual exclusion, hold and wait, no preemption (nobody can take a held lock away), and a circular wait. Remove any one and deadlock is impossible.
Seeing one. Two Python threads take two locks in opposite orders (deadlock.py: a logger takes metrics_lock then ckpt_lock, a saver the reverse), then are inspected from outside measured here. The figure replays the recording:
with metrics_lock:; it then sleeps 0.1 s holding it.metrics_lock.join() for logger.deadlock.py:13, saver at deadlock.py:21 and the main thread in join; /proc shows all three threads in state S, wait channel futex_wait_queue_me.--ordered, saver takes metrics_lock first, so it waits holding nothing; logger finishes, then saver, and the run prints "finished".The signature of a deadlock: every thread in state S (sleeping), every wait channel futex_wait_queue_me, 0% CPU, and py-spy pointing at the two with lines. A busy-looping bug looks the opposite (state R, 100% CPU).
| Break | How | Cost |
|---|---|---|
| Circular wait | A global lock order: every thread takes locks in the same order (by level, or by address). The standard cure. The Linux kernel checks it at run time with lockdep, which records the order every lock class was ever taken in and warns at the first inversion, before any deadlock happens (lockdep design) | Discipline; hard across libraries and callbacks |
| Hold and wait | Take all locks at once (behind one outer lock), or hold none while calling out | Less concurrency |
| No preemption | trylock, and on failure release everything and retry, with random backoff | Can livelock: threads keep backing off and retrying without progress |
| Mutual exclusion | Lock-free data structures (section 2, depth) | Much harder to write |
__del__) while holding a lock (copy what you need, release, then call): thread A holding L and calling logging.info() while a handler thread holds the handler's lock and wants L is a circular wait, although logging is "thread-safe" (each call is safe on its own); lock.acquire(timeout=...) in Python turns a silent hang into an error you can log; faulthandler.dump_traceback_later(timeout) prints every thread's stack if the job stops progressing; glibc's PTHREAD_MUTEX_ERRORCHECK returns EDEADLK when a thread re-locks a mutex it holds; ThreadSanitizer (-fsanitize=thread) reports lock-order inversions as well as data races.The training-job deadlock everyone meets is not two locks but fork while another thread holds one: the child gets a copy of the locked lock and no thread to release it. The root's Debug lab reproduces it ("A worker hangs forever: fork while another thread holds a lock") and Processes covers start methods (spawn or forkserver, or fork before starting threads); it is why Python 3.14 made forkserver the default on Linux. Databases face the same four conditions with a different cure (detect the cycle and abort a victim): Transactions and concurrency.
Lu et al. studied 105 concurrency bugs in MySQL, Apache, Mozilla and OpenOffice: 74 were not deadlocks and 31 were; 97% of the non-deadlock bugs were of two kinds (as summarised in OSTEP ch. 32, from Learning from Mistakes, ASPLOS 2008):
if (p) use(p); while another thread sets p = NULL. Fix: one lock around both steps.from source measured here
CPython's global interpreter lock lets one thread at a time run Python bytecode, and it is built from exactly the parts of sections 4 and 5: "The GIL is just a boolean variable (locked) whose access is protected by a mutex (gil_mutex), and whose changes are signalled by a condition variable (gil_cond)" (Python/ceval_gil.h L13-16, v3.11.2). A thread that wants the GIL waits on the condition variable for at most the switch interval (5 ms by default, DEFAULT_INTERVAL 5000 µs, L91); if the wait times out it sets gil_drop_request, which the running thread checks between bytecodes; the running thread then releases the GIL and waits until someone else has taken it, so it cannot grab it straight back. A thread blocked in a system call (sleep, recv, read) or in C code that releases the GIL (NumPy, PyTorch operators) lets others run meanwhile; how to write Python around it is Python: concurrency, asyncio and the GIL's.
What it does to latency. A thread waking from I/O must get the GIL back; if another thread is busy in Python it waits up to a whole switch interval. An "I/O" thread sleeping 2 ms, 300 times, next to 0, 1 or 2 threads doing pure-Python arithmetic, on 2 CPUs (gil_latency.py; median of 3 runs). Predict how late it wakes next to one busy thread:
Next to one busy thread the I/O thread wakes 8.0 ms late (the 5 ms interval plus the wake-ups on both sides); next to two, 17.5 ms, with a 99th percentile of 86.9 ms, because it competes with another waiter for each hand-over. sys.setswitchinterval(0.0005) brings it to 1.4 ms, at the price of more switching. This is the convoy effect David Beazley measured in 2010 for the GIL that 3.2 introduced (Understanding the Python GIL): a heartbeat to the cluster scheduler, a metrics sender or an asyncio loop next to Python preprocessing is delayed by milliseconds.
Python 3.14's free-threaded build (python3.14t, officially supported since 3.14, PEP 779; design in PEP 703) removes the GIL. Removing one lock means every object needs another way to stay consistent, and the replacement is this page's toolbox applied to the interpreter:
d[k] += 1 from two threads is still section 2's lost update, now happening for real.Measured in Python: concurrency, asyncio and the GIL, section 1 (Python 3.14.8, a 10-CPU laptop under load, best of three): counting primes four times took 0.99 s on four threads with the GIL (0.96 s serially) and 0.37 s on four threads free-threaded (0.94 s serially); four processes took 0.36 s and 0.31 s. Scaling, overhead and which extensions are ready are measured in its section 3.
ch. 33 Event-based concurrency from source measured here
A server with thousands of open connections (an inference server streaming tokens, a data service) spends almost all its time waiting. Blocking I/O with a thread per connection works, but each thread is a stack, a kernel task and a context switch per event. 2,000 connections, each a Unix socket pair, served by one thread each or by one asyncio loop (conns.py; median of 3):
The alternative is non-blocking I/O plus one question to the kernel, "which of these file descriptors are ready?". A descriptor (the integer naming an open file, pipe or socket) is ready when a read or write on it would not block; put it in non-blocking mode (O_NONBLOCK) and a read that would block returns EAGAIN instead. The designs differ in how the question is asked:
select (BSD, 1983) passes three bitmaps of descriptor numbers, poll (System V) an array of {fd, events}. On every call the kernel copies the list in, checks every descriptor, registers a wait on each, sleeps, and on wake-up checks them all again (fs/select.c, v5.10); the program then scans the whole list again. Cost grows with the number watched. FD_SETSIZE is 1024, so select cannot watch descriptor 1024 or higher at all (select(2)).epoll_ctl(ADD) registers a descriptor once into an interest list (a red-black tree) with a separate ready list (fs/eventpoll.c L195-204). When data arrives, the socket's wait-queue callback ep_poll_callback appends that one item to the ready list (L1244-1248); epoll_wait just takes items off it. Cost follows the number ready.Step one input through the designs: eight connections, data arriving on connection 2, then 5, then 2 again, then 7. Predict which design makes the fewest system calls before you switch to it; the counters at the top of the figure keep the totals.
select and poll check every connection on every event; epoll touches only the ready one; io_uring does the read itself.
recv() on its own socket: eight system calls, eight stacks of 8 MiB address space.recv() returns the data; it calls recv() once more. The other seven never woke.recv() again.select() or poll() passes the whole list: the kernel copies it in, checks each descriptor (none ready), registers a wait on each and sleeps.poll took 650 µs here; select cannot watch descriptor 1024 or higher at all.epoll_create1, then epoll_ctl(ADD) once per descriptor: the interest list lives in the kernel, as a red-black tree.ep_poll_callback, appends it, whatever N is; epoll_wait returns exactly [2]. Level-triggered, it stays listed until the data is read.epoll_wait took 352 ns here.io_uring_setup maps a submission ring and a completion ring into both program and kernel; the program writes eight read requests (SQEs) and submits them with one io_uring_enter.io_uring_enter waits for at least one (with SQPOLL and busy rings even this call is not needed).read()) and writes a fresh read SQE for connection 2.io_uring_enter per wait and none per read; on cached file blocks it made 512 calls instead of 16384 (below).The same difference at scale, with N pipes watched and exactly one readable (evloop.c, one call returning one ready descriptor):
The chart shows the measured cost of one readiness question against the number of descriptors watched; the sliders below it scale the same measurements to a server: the connections watched and the message rate give each design's cost as a share of one CPU.
Scale it. Move the connections watched, and the message rate, to see each design's cost per readiness question as a share of one CPU (log-log interpolation between the measured points 1, 10, 100, 300, 500, 1,000, 3,000 and 10,000; thread memory from the measured 2,000-thread run). At 10,000 idle clients, epoll_wait costs 352 ns against 393 ns at 100; poll 650 µs: from 100 to 10,000 watched, poll grows about a hundredfold, and select cannot go past descriptor 1023 at all.
By default epoll is level-triggered: a descriptor is reported on every epoll_wait while data remains, because after reporting it the kernel puts it back on the ready list (L1758-1771). With EPOLLET it is edge-triggered: reported once per change (new data arriving), and not put back. Write 10 bytes to a pipe, read only 4, and ask again measured here:
Edge-triggered is cheaper (no re-reporting) but has one rule: after an edge, read (or accept, or write) until EAGAIN, or the remaining 6 bytes sit unreported until more data happens to arrive, which on a quiet connection is never. asyncio and libuv use level-triggered mode, tokio edge-triggered; macOS and the BSDs have the same design as kqueue (depth block below).
Tokio's I/O layer, mio, registers every descriptor edge-triggered (let mut kind = EPOLLET;, mio src/sys/unix/selector/epoll.rs L115, v1.0.4) and its readiness tracking enforces the rule; Python's asyncio and libuv use level-triggered mode. macOS and the BSDs have the same idea as kqueue (kqueue(2)), with filters for sockets, files, processes, signals and timers in one call; Python's selectors module prefers it where it exists (Lib/selectors.py L610-618).
All follow the readiness model (the kernel says "you can read now"; the program then makes the read itself: one system call per read and write, plus one per wait). Python asyncio waits with epoll, level-triggered, via selectors.EpollSelector; Node.js's libuv and uvloop with epoll_pwait plus a thread pool for file I/O and DNS; Rust's tokio with epoll, edge-triggered, via mio, under a work-stealing pool of threads. Their loops are taught in Python: concurrency, asyncio and the GIL, section 2, Rust: async with tokio, services with axum, and CLIs and JavaScript: the event loop, promises and streams, section 2.
| Runtime | Its loop, in one line |
|---|---|
| Python asyncio | _run_once: compute a timeout from the earliest timer, event_list = self._selector.select(timeout), queue the ready callbacks, run them (base_events.py L1884, v3.11.2). The root's trace shows its epoll_pwait calls |
| Node.js (libuv), uvloop | uv__io_poll calls epoll_pwait(epollfd, events, ..., timeout, sigmask) (src/unix/linux.c L1432, v1.48.0). Since 1.45 libuv can batch through io_uring; the SQPOLL ring for file operations is opt-in (UV_USE_IO_URING=1) and refused on kernels older than 5.10.186 because "the sqpoll thread uses 100% CPU" there (v1.51.0 L480-497) |
| Rust tokio | When a task's read returns WouldBlock its waker is parked until mio reports the descriptor. Rust: async with tokio, services with axum, and CLIs measures what blocking the runtime does |
One io_uring_enter call submits a whole batch and can wait for completions; with IORING_SETUP_SQPOLL a kernel thread polls the submission ring and the program makes no system call at all. The rings are single-producer single-consumer queues (section 2, depth). On this lab's kernel 5.10 measured here (raw output, with the setup failures, in the closed block below), reading 16,384 cached 4 KiB blocks, io_uring at depth 32 made 512 system calls instead of 16384, and the time per block fell from 1171 to 908 ns (22% less; medians of 3 noisy runs, which overlap): with the data already in memory, the 4 KiB copy and the per-request bookkeeping remain and only the system-call entries are saved. io_uring pays off when operations really wait (disk, network) and many are in flight, when operations are tiny, or with SQPOLL and registered buffers on newer kernels not run here.
First, io_uring_setup failed in a default Docker container: Linux 5.10 charges the rings to the user's locked-memory limit (RLIMIT_MEMLOCK, 64 KiB in Docker) unless the process has CAP_IPC_LOCK (fs/io_uring.c L7869-7876 and L9274, v5.10), and the counter is per user, shared by every container running as root; the run passed --ulimit memlock=-1. Linux 5.12 moved the rings to memory-cgroup accounting from source (the ring_pages charge is gone from fs/io_uring.c at v5.12). Second, SQPOLL needs CAP_SYS_ADMIN before 5.11 (L7786).
uvloop.run(run_server(args)) (vllm/entrypoints/launchers/api_server/entry.py L222, v0.31.0) and SGLang passes loop="uvloop" to uvicorn (http_server.py L2713, v0.5.21): uvloop is libuv underneath, so one thread streams tokens to many clients while the GPU work runs in an engine loop. A blocking call in an async handler (a synchronous tokenizer call, requests.get, a big JSON encode) stalls every connection on that loop; use asyncio.to_thread or a process pool (Rust: async with tokio, services with axum, and CLIs measures the stall). Data clients that stream shards from object storage use the same machinery (aiohttp, or Rust/C++ readers on tokio or io_uring). At 10,000 sockets the open-file limit, ulimit -n, must allow them.The three differ in what they share and what a wait costs, so the choice follows from what the work waits on and whether it computes in Python:
fork after threads exist copies held locks (section 6); spawn and forkserver avoid it."About 7 KiB" is derived: 13 × 1,024 KiB / 2,000 threads = 6.7 KiB. Real systems combine them: vLLM is an event loop in front of an engine process; a training job is processes (workers) of threads (pools).
measured here from source GPU parts not run here
The root's job (2 DataLoader workers, fork, torch.set_num_threads(n)), stopped while stepping and looked at three ways: /proc/<pid>/task/* (name, state, wait channel), py-spy dump (the Python threads), and gdb backtraces of every thread classified by the functions on their stacks (job_threads.sh, classify_threads.py). Predict how the futex count per step changes with the torch thread count, then switch:
do_spin and then sleeping in futex_wait), two Python QueueFeederThreads (each multiprocessing.Queue has one, pickling what put() buffered into the pipe to the worker), and a libtorch_cpu thread asleep on a futex.pt_data_worker by PyTorch) waits in poll for the next indices, plus a feeder thread for its result queue and a _serve thread: multiprocessing's resource sharer, which hands file descriptors for shared-memory tensors to the main process over a Unix socket (the recvmsg calls).The thread count is a design input. Each worker runs its own copy of every thread pool a library creates (PyTorch sets torch.set_num_threads(1) in workers, but tokenizers, OpenCV and NumPy's BLAS have their own), and in a container every thread counts against pids.max and shares the CPU quota (the root's Debug lab, "Too many threads for the CPUs you have"; scheduling is Scheduling and CPU time). os.cpu_count() reports the machine, not the quota: multiply by the number of worker processes and every library's own pool.
top -H or ps -L to confirm all threads sleep; /proc/<pid>/task/*/wchan (futex waits mean locks, queues or condition variables; poll or read means waiting for data); py-spy dump --pid for Python stacks on every rank and worker; gdb -p <pid> -ex "thread apply all bt" for native threads; then find who should have released or sent what each one waits for. In a distributed job the usual cause is not a lock but a collective that one rank never reaches (one rank skipped an all-reduce, or is stuck in its data loader): every other rank's main thread sits in a CUDA synchronisation or a futex while the GPU kernel spins waiting for the missing peer, and the watchdog fires after the process group's timeout. py-spy dump --pid on every rank (or PyTorch's flight recorder, TORCH_NCCL_TRACE_BUFFER_SIZE) shows which rank is somewhere else; Distributed Training covers the collectives, and GPU-side concurrency (streams) is Streams, CUDA graphs and multi-GPU programming's.| Thread | Who starts it | What it does, and how it waits |
|---|---|---|
| pin_memory thread | DataLoader with pin_memory=True (dataloader.py L1198, v2.14.1) | Takes batches from the workers' result queue, copies them into page-locked host memory so the copy to the GPU can be asynchronous, puts them on the queue the loop reads. It calls torch.set_num_threads(1) and polls its queue with a timeout so it notices shutdown (pin_memory.py L18-30) |
| NCCL watchdog | ProcessGroupNCCL (ProcessGroupNCCL.cpp L2152-2155) | Wakes every 100 ms (kWatchdogThreadSleepMillis, L493) to check whether collectives have finished or timed out; on a timeout it aborts the communicator so a hung rank fails instead of waiting forever |
| NCCL heartbeat monitor | same (L1772-1790) | Watches the watchdog: if it has not beaten for TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC (8 minutes by default), kills the process. A deadlock detector for the deadlock detector |
| NCCL Progress thread | NCCL, one per GPU and communicator (src/proxy.cc L1030-1035, v2.32.3-1) | Drives network transfers (InfiniBand, sockets) for the GPU's kernels. While operations are in flight it busy-polls and calls std::this_thread::yield() when nothing progressed (L986-1006); when idle it sleeps on a condition variable (section 5). A spinning thread per GPU is why NCCL performance is sensitive to CPU affinity and to CPU quotas |
| NCCL Service, UDS threads | NCCL (L2157-2163) | Answer setup requests from other ranks over sockets, asleep in poll otherwise |
clone flags that share the address space, file table and signal handlers with its creator (CLONE_VM, CLONE_FILES, CLONE_SIGHAND, CLONE_THREAD); a process gets copies (copy-on-write for memory). Threads communicate through memory for free and need synchronisation; processes need IPC but are isolated from each other's crashes, and in CPython each has its own GIL.futex_wait(word, 2), which sleeps only if the word is still 2, checked in the kernel under the wait-queue lock. Unlock: exchange in 0; if the old value was 2, futex_wake(word, 1). Uncontended: two atomic instructions, no system call.d[k] += 1) is still a race and needs a lock.| Chapter | Here |
|---|---|
| 26 Concurrency: an introduction (pdf) | sections 1, 2 |
| 27 Interlude: thread API (pdf) | section 1 |
| 28 Locks (pdf) | sections 2, 3, 4 (Peterson, spin, yield, futex) |
| 29 Lock-based concurrent data structures (pdf) | section 3 (contention), section 2 depth |
| 30 Condition variables (pdf) | section 5, the scheduler lab in section 4 |
| 31 Semaphores (pdf) | section 5 |
| 32 Common concurrency problems (pdf) | section 6 |
| 33 Event-based concurrency (pdf) | section 8 |
OSTEP's homework simulators for these chapters (x86.py for races and locks, the deadlock and condition-variable programs) are covered by the root's OS simulators tab and this page's scheduler lab (section 4).
Threads, races, locks, the futex (with the scheduler lab), condition variables, deadlock, the GIL and free-threaded Python, event-driven I/O (with the five-designs walkthrough), choosing a model, and the training job's threads. 34 minutes, plus 14 in closed details
The whole OS for one training job. Its OS simulators tab runs OSTEP's race, lock and deadlock programs; its Debug lab reproduces the fork-with-a-held-lock hang. 24 minutes, plus 7 in closed details and the labs
fork, exec, signals, file descriptors, start methods: the process side of section 1 and the descriptors of section 9.
Context switches, CFS and EEVDF, CPU quotas: what decides which of your threads runs.
Why 2,000 thread stacks reserve 18 GB and use 13 MiB; shared memory between processes.
malloc's per-thread arenas, a concurrency design.
Where io_uring and asynchronous checkpoint writes pay off.
pids.max counting threads, seccomp profiles that block io_uring.
Why cross-CPU wake-ups cost more in a virtual machine.
The memory model with a measured reordering, false sharing (section 8). 33 min, plus 21
llama.cpp's CPU thread pool and its barriers (section 9). 37 min, plus 39
Threads, the GIL and processes in practice; asyncio from the event loop up; free-threaded 3.14t scaling. 19 min, plus 10 in closed details
Threads without data races, Send and Sync; then tokio, and blocking the runtime measured. threads page 16 min; async page 27 min
libuv's event loop phases, one step at a time; worker threads. 19 min, plus 11 in closed details
Locks, deadlock detection and MVCC in databases: the same problems at another layer. about 43 minutes
Producer/consumer between services. about 40 minutes
Sockets and the networking the event loops serve. about 49 minutes
The collectives that NCCL's threads progress. about 32 minutes
Concurrency on the GPU side: streams, events and NCCL from the device's point of view.
Failures around the job: detection timeouts at every layer and the recovery designs. about 41 minutes
DataLoader, thread settings and the libraries whose threads section 10 counts. about 30 minutes
Arpaci-Dusseau and Arpaci-Dusseau; free. The spine of sections 1 to 6. about 5 hours
Ulrich Drepper, 2011: three mutex designs on futexes, two of them broken, and why. The source of section 4's protocol. 45 minutes
The interfaces, with the edge-triggered pitfalls spelled out in epoll(7). 20 minutes each
Jens Axboe, 2019: why io_uring exists and how the rings work. 40 minutes
Paul McKenney: locking, memory barriers and RCU from the Linux kernel's point of view; the pro-level follow-up. a book; chapters of 1 to 2 hours
Allen Downey: synchronisation puzzles with semaphores; good practice for interviews. puzzles, 15 minutes each
David Beazley, 2010: the GIL's switching and the convoy effect, measured. 30 minutes
Lu, Park, Seo and Zhou, ASPLOS 2008: 105 real concurrency bugs classified. 40 minutes
Why io_uring is disabled in many production environments. 10 minutes
src/inputs/source_lines.txt. Measurements: Docker Desktop Linux VM (5.10.104-linuxkit, arm64, 5 CPUs) on an Apple M1 Pro, 2026-10-05, image kb-os-conc:1 (src/runs/Dockerfile); rerun everything with sh src/run_all.sh.