Concurrency: threads, locks, futexes, deadlock, and event-driven I/O

What lets the many threads of one training job share memory and wait for each other without corrupting data or wasting CPUs: threads, races and atomics, locks and the futex under every Linux lock, condition variables, deadlock, the GIL and free-threaded Python, and the event loops (epoll, kqueue, io_uring) that async servers are built on. Linux, glibc and CPython source at pinned tags; real runs on Linux 5.10. A child page of Topic: operating-systems. Data as of October 2026. Reading: 38 min, plus 15 in closed details.

The idea in one screen

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):

  1. Two places to wait. Above, user space: threads and the memory they share. Below, the kernel, which can take a thread off its CPU and keep it in a queue. A lock, condition variable, queue, barrier or the GIL is a word in user memory; the kernel is involved only when the word says someone must sleep.
  2. Fast path: a lock is a word. Thread A takes the lock word w from 0 to 1 with one compare-and-swap: 10.1 ns for a pthread_mutex_t here, no system call.
  3. A real wait parks in the kernel. B and C find 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.
  4. Unlock wakes one. A unlocks, sees 2, and calls 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.
  5. Waiting for I/O: register once. An event loop registers its sockets once with epoll (epoll_ctl ADD); the kernel keeps them in an interest list, and the loop's one thread sleeps in epoll_wait.
  6. Only the ready one comes back. Data arrives on socket 5; the socket's callback puts it on the ready list, and 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.

Thread
a flow of control (registers, stack) that shares its process's memory and files.
Race, data race
a result that depends on timing; a data race is two unordered accesses to one location, at least one a write.
Critical section
code on shared data that at most one thread may run at a time (mutual exclusion).
Atomic instruction
a read-modify-write of one word that no other core can split (CAS, exchange, fetch-and-add).
Memory order
which of a core's writes other cores see, and in what order; acquire and release say what must not be reordered.
Futex
a lock word in user memory plus two kernel calls: sleep if the word still equals v, wake n sleepers.
Condition variable, semaphore
sleep until another thread says a condition may hold; a counter that blocks at zero.
Deadlock
a cycle of threads each holding what the next one waits for.
GIL
CPython's single lock around bytecode; the free-threaded build replaces it with per-object locks.
Readiness, completion
"this descriptor can be read now" (epoll, kqueue) against "this read is done" (io_uring).
The page in one table: each mechanism, its cost here, where it bites (reference)

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):

main process (the training loop) ├─ MainThread runs forward, backward, optimizer step; holds the GIL while in Python ├─ QueueFeederThread x2 pickles batch indices into each worker's pipe └─ native threads OpenMP's pool for PyTorch's math; asleep in futex_wait between operators worker process x2 (fork of main) ├─ pt_data_worker reads samples, builds a batch, puts it on the result queue └─ helper threads queue feeder, file-descriptor server; asleep in poll or futex_wait
MechanismThe problem it solvesCost measured hereWhere it bites in ML workSee it with
ThreadSeveral flows of control sharing one address spacecreate + join 136.0 µs in this VM; 8 MiB of address space each, almost none of it touchedThread pools sized from the machine, not the containerls /proc/<pid>/task, top -H
Atomic instructionA read-modify-write no other core can split8.3 ns per update, uncontendedReference counts, counters, lock wordsthe assembly (ldadd, ldaxr/stlxr)
Lock (mutex)Only one thread at a time in a critical section10.1 ns uncontended; a spinlock wastes whole time slices when the holder is preemptedLogging, metrics, allocator and queue locks under many threadsperf lock, strace -f -e futex
FutexSleep in the kernel only when a lock is really taken0 system calls uncontended; a wake-up costs 1.7 µs on one CPU, 23.5 µs across CPUs in this VMEvery PyTorch, NCCL and Python lock and queue/proc/<pid>/task/*/wchan
Condition variable, semaphoreSleep until something is true ("a batch is ready")Mesa semantics: woken is not "true"; one shared condition variable hangsProducer/consumer queues in loaders and serverspy-spy, gdb
DeadlockA cycle of threads each waiting for the nextHangs forever at 0% CPUFork with a held lock; lock-order bugs in callbackspy-spy dump, wchan
GILCPython's one lock for all Python bytecodeAn I/O thread wakes 8.0 ms late next to one busy Python threadLatency of a data or serving thread next to Python worksys.getswitchinterval(), py-spy
epoll, io_uringOne thread waiting on thousands of connections or I/Ospoll on 10,000 descriptors 650 µs per call, epoll_wait 352 nsAsync model servers, data streaming clients, asynciostrace -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.

1. Threads: several flows of control, one address space

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:


CLONE_VM, CLONE_FILES, CLONE_FS, CLONE_SIGHANDshare the address space, the file-descriptor table, the working directory, and the signal handlers
CLONE_THREADsame thread group: same process id for getpid(), a new thread id (gettid())
CLONE_SETTLSpoint the thread-pointer register (tpidr_el0 on arm64, fs on x86-64) at this thread's thread-local storage
CLONE_CHILD_CLEARTIDwhen the thread exits, the kernel writes 0 to its id word and does a futex wake on it: that is how pthread_join learns it ended
Cost measured here: creating and joining an empty thread took 136.0 µs with 4 CPUs available and 12.0 µs pinned to one CPU (best of 5 × 2000); the difference is the cross-CPU wake-up, unusually expensive in this VM (section 4). Each thread's stack reserves 8 MiB (from ulimit -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").

One address space, shared; each thread keeps its own registers, stack and thread-local storage

What clone's flags (left) share, and what each thread keeps for itself.

Stack guard, clone3, thread-local storage, and what exit() does (depth)

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.

2. Races, atomic instructions and memory order

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:

  1. Start: count = 41. T1 and T2 each run count = count + 1: load into a register, add 1, store back. The values are illustrative.
  2. T1 loads 41. The value travels from memory into T1's register.
  3. T2 loads before T1 stores. On another core, or after the scheduler switched threads, T2 also reads 41.
  4. T1 adds 1 in its register. Its register says 42; memory still says 41.
  5. T1 stores 42.
  6. T2 adds 1 to the 41 it loaded. Its register says 42 as well.
  7. T2 stores 42 over T1's 42: a lost update. Two increments, and count rose by one. It needs exactly this interleaving, so it happens rarely and never on demand.

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:

Fetch-and-addold = *p; *p = old + v in one step. arm64 v8.1 has ldadd; x86-64 has lock xadd. Counters and reference counts.
Exchange (test-and-set)old = *p; *p = v. The simplest lock: while (xchg(&l, 1) == 1) ;
Compare-and-swap (CAS)if *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 raw output of the ten runs (evidence)

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, and lock-free structures in brief (depth)

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.

3. Locks: spin, yield, or sleep

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:

Spinkeep retrying the atomic exchange. Best when the holder runs on another core and will release within nanoseconds; terrible when the holder is not running, since the spinner burns its whole time slice.
Yieldretry, calling sched_yield() after each failure (OSTEP 28.13): a system call per failed attempt, and no promise about who runs next.
Sleepask the kernel to put the thread on a wait queue and wake it at release: two system calls and a wake-up when contended, nothing else.
Spin, then sleep(two-phase or adaptive) spin briefly in case the holder is about to release, then sleep. glibc's 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).
  • Uncontended, a good lock costs about one atomic instruction (9.2 ns for the hand-built futex lock, 10.1 ns for 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.
  • Contended on enough CPUs, spinning burns CPU: with a short critical section the spinlock used 910.3 ns of CPU per acquisition against 437.2 ns for the mutex, and was slower in wall time too, because four cores fighting over one cache line slow each other down.
  • With more threads than CPUs, a spinner waits for a thread that is not running. On one CPU with a long critical section the holder is often preempted inside it, and each spinner burns a whole time slice: 1492.5 ns per acquisition against 815.9 ns for the mutex and 791.5 ns for one thread doing the same work alone. In a container with a one-CPU limit and a long critical section, that slice is milliseconds, and under a CPU quota the whole cgroup can be throttled until the next 100 ms period (the root's Debug lab, "CPU limit" cases).
  • Hammering a lock rewards unfairness: with no work the yield lock looks fastest because the releasing thread retakes it while its cache line is hot. A ticket lock (OSTEP 28.11: fetch-and-add a ticket, wait for your number) is fair and slower.

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.

A good lock costs one atomic instruction until it is contended; then the situation picks the winner

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.

4. The futex: how every Linux lock sleeps

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:

futex_wait(addr, val)"if *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.
futex_wake(addr, n)"wake up to 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:

  1. Uncontended: one CAS. A finds 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.
  2. B finds it taken and marks 2. B's CAS fails; xchg(w, 2) returns 1, not 0, so B does not own the lock, but w now says "someone may be waiting".
  3. futex_wait(w, 2): compare, then sleep. B enters the kernel (a system call, about 0.3 µs). The kernel locks the hash bucket for w's address, reads w, finds it still 2, and queues B. B is off the CPU.
  4. C queues behind B. C sees w = 2 and goes straight to futex_wait(w, 2). Two sleepers; the word in user memory is all that records them.
  5. Unlock that saw 2: futex_wake(w, 1). A swaps in 0, gets back 2, so it asks the kernel to wake one sleeper. B leaves the queue: 1.7 µs to run again on the same CPU, 23.5 µs across CPUs in this VM.
  6. B retakes the lock as 2. B's xchg(w, 2) returns 0: B owns the lock, and leaves it at 2 because it cannot know whether C is still asleep.
  7. B unlocks, C runs. B's unlock sees 2 and wakes C, which takes the lock the same way. C's own unlock will make one wake call that finds nobody: the price of never missing a sleeper.

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 the kernel must compare: the lost wake-up

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:

You are the scheduler: break the lock, or prove you cannot

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.

One contended lock, four ways: before and after the futex

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.

The futex frees the CPU for C; each hand-off now pays a wake-up

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.

In ML work Python's 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).
Where the sleepers are kept, shared futexes, and the rest of the futex family (depth)

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_WAIT_BITSET with FUTEX_CLOCK_REALTIME: a wait with an absolute deadline; glibc uses it for timed waits and POSIX semaphores (the trace above).
  • FUTEX_CMP_REQUEUE: wake one waiter and move the rest from a condition variable's futex to the mutex's, so a broadcast does not wake a herd that would immediately fight for the mutex (the thundering herd). glibc 2.25 (2017) replaced its condition variables with an algorithm based on groups of waiters that never requeues (no requeue call appears in nptl/pthread_cond_wait.c, glibc 2.36); the operation remains in use for priority-inheritance locks.
  • FUTEX_LOCK_PI: priority inheritance; the kernel knows the owner (its thread id is in the word) and boosts it while a higher-priority thread waits. It fixes priority inversion, the bug that kept resetting NASA's Mars Pathfinder in 1997 (account by Glenn Reeves).
  • Robust futexes: the kernel walks a per-thread list at exit and marks locks held by a dead thread (EOWNERDEAD), for locks in memory shared between processes.
  • futex_waitv (Linux 5.16) waits on several futexes at once, added for Wine and game engines (futex2 docs); not on this 5.10 kernel.

5. Waiting for something: condition variables, semaphores, barriers

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.

The condition-variable runs, and reader-writer locks (depth)

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.

6. Deadlock, and the other concurrency bugs

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:

  1. logger takes metrics_lock. Line 11, with metrics_lock:; it then sleeps 0.1 s holding it.
  2. saver takes ckpt_lock. Line 19, the opposite order. Each thread now holds one lock: mutual exclusion, and hold and wait.
  3. logger asks for ckpt_lock and parks. Line 13: the lock is held, so logger sleeps on its futex, still holding metrics_lock.
  4. saver asks for metrics_lock: a cycle. Line 21: saver parks too. Each waits for the other and nobody can take a held lock away: a circular wait in the wait-for graph. The main thread waits in join() for logger.
  5. What the recording shows. py-spy finds logger at 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.
  6. One lock order removes the cycle. Run with --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).

BreakHowCost
Circular waitA 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 waitTake all locks at once (behind one outer lock), or hold none while calling outLess concurrency
No preemptiontrylock, and on failure release everything and retry, with random backoffCan livelock: threads keep backing off and retrying without progress
Mutual exclusionLock-free data structures (section 2, depth)Much harder to write
Fixes and tools One lock order per program, written down; never call unknown code (callbacks, logging handlers, __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.

Most concurrency bugs are not deadlocks (depth)

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):

Atomicity violationcode assumed two steps happen together, and another thread ran between them: if (p) use(p); while another thread sets p = NULL. Fix: one lock around both steps.
Order violationcode assumed A happens before B, and nothing enforced it: a thread uses an object before its creator finished initialising it. Fix: a condition variable or semaphore that B waits on.

7. The worked case: the GIL and free-threaded Python

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.

Next to busy Python threads, a 2 ms sleep comes back a whole switch interval late

The free-threaded build: the same job, before and after

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:

  • Built-in containers lock themselves. "Built-in types like dict, list, and set use internal locks to protect against concurrent modifications in ways that behave similarly to the GIL" (free-threading how-to, 3.14): a dictionary never corrupts, but d[k] += 1 from two threads is still section 2's lost update, now happening for real.
  • Reference counts stop being a shared hot word. "Biased reference counting, with a fast-path for objects owned by the current thread and a slow path for other objects" (same page): the owner changes its count with a plain add, other threads with an atomic one (section 2's 8.3 ns). Some objects (code constants, interned strings) are immortal, so their count is never written at all, and objects such as module functions use deferred reference counting.
  • The cost: "On the pyperformance benchmark suite, the average overhead ranges from about 1% on macOS aarch64 to 8% on x86-64 Linux systems" for single-threaded code (same page), and every C extension must declare support or importing it turns the GIL back on.

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.

One lock for the interpreter, or a small lock and a thread-owned reference count per object

8. Event-driven I/O: one thread, thousands of waits

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, poll: the whole list, every timeselect (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: the list lives in the kernel(Linux 2.6, 2002) 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.
io_uring: completions, not readiness(Linux 5.1, 2019) "do these operations and tell me when they are done": the program writes submission queue entries (SQEs) into a ring shared with the kernel, the kernel does the I/O and writes completion queue entries (CQEs) into another (io_uring(7)).

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.

  1. One thread per connection. Eight threads, each blocked in recv() on its own socket: eight system calls, eight stacks of 8 MiB address space.
  2. Data arrives on connection 2. The kernel puts it in the socket buffer and wakes the one thread sleeping on it: a context switch.
  3. Thread 2 handles it and sleeps again. Its recv() returns the data; it calls recv() once more. The other seven never woke.
  4. Connections 5, 2 and 7. The same each time: the thread that owns the connection wakes, handles it and calls recv() again.
  5. At 2,000 connections. Measured (table above): 2,001 threads and 18683 MiB of address space, but only 13 MiB more resident memory; idle threads are cheap, each wake-up is a context switch.

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.

poll's cost grows with every descriptor watched; epoll_wait's stays flat

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.

Level-triggered and edge-triggered

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).

What each runtime waits with, and its loop in one line (depth)

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.

RuntimeIts 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), uvloopuv__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 tokioWhen 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

io_uring on a real kernel

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.

io_uring is often unavailable in containers
Google reported that 60% of the Linux kernel exploits submitted to its kCTF bug bounty in the year to June 2023 used io_uring, and disabled it in ChromeOS and on its production servers (Google security blog, 2023-06-14). Docker 25.0 blocks the io_uring system calls in its default seccomp profile (moby #46762); this lab's Docker 20.10 still allows them.
The io_uring runs, and why io_uring_setup failed here at first (depth)

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).

In ML work Model servers are event loops: vLLM's OpenAI-compatible server is a uvicorn server started with 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.

9. Choosing threads, processes or an event loop

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:

Threads

  • Share memory for free, so shared state needs locks (sections 2 to 6).
  • Create + join 136.0 µs here; 8 MiB of address space each, about 7 KiB resident when idle (13 MiB added for 2,000 threads).
  • Parallel for native code that releases the GIL, and for Python on the free-threaded build; under the GIL, concurrency for waiting only.
  • No isolation: a crash or a corrupted heap takes every thread down.

Processes

  • A separate address space: a crash or a corrupted heap in one cannot touch the other, and in CPython each process has its own GIL.
  • Data moves by pickling or shared memory; PyTorch's DataLoader uses worker processes for exactly that trade.
  • fork after threads exist copies held locks (section 6); spawn and forkserver avoid it.
  • Start-up and copies cost: the four-process pool in Python: concurrency, asyncio and the GIL, section 1 ran 2.7 times faster, not four.

One event loop

  • One thread, thousands of waits: 2,000 connections added 5 MiB and started serving in 22 ms (section 8).
  • Callbacks run one at a time, so no locks between them, but one blocking call or CPU-heavy handler stalls every connection.
  • Needs non-blocking libraries all the way down; CPU work goes to a thread or process pool.

"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).

Waiting picks between an event loop and threads; computing in Python picks processes (or free-threaded threads)

10. In a training job: every thread, and what it waits on

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:


  • The main process runs the training loop in its main thread. Its other threads are PyTorch's OpenMP pool (libgomp; between operators they wait at a barrier, spinning briefly in 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.
  • Each worker (named 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).
  • Nearly every thread is asleep on a futex. Attached for 3 seconds with strace, the job made about 59 futex calls per training step with 2 torch threads (39 with 1, 86 with 4), about a fifth of them EAGAIN (section 4): barrier wake-ups for each parallel operator and the queues' locks and semaphores. Strace slows the job about tenfold: count, do not time, under it.

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.

When a job hangs at 0% CPU 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.
On a GPU node: the CPU threads you do not see (from source) (depth)
ThreadWho starts itWhat it does, and how it waits
pin_memory threadDataLoader 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 watchdogProcessGroupNCCL (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 monitorsame (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 threadNCCL, 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 threadsNCCL (L2157-2163)Answer setup requests from other ranks over sockets, asleep in poll otherwise

Depth: interview rehearsal and the OSTEP map

Interview questions, with model answers (optional)
What is the difference between a process and a thread on Linux?
Both are tasks the scheduler runs. A thread is created with 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.
How does a mutex work, down to the kernel?
A word in user memory. Lock: CAS 0 to 1; if that fails, exchange in 2 ("contended") and call 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.
Why must the kernel re-check the value in futex_wait?
To avoid the lost wake-up: between a user-space check and going to sleep, the holder could release and send a wake-up to a thread not yet asleep. Comparing under the hash-bucket lock makes "check and sleep" atomic with respect to wakers.
Spinlock or mutex?
Spin only if the expected wait is shorter than a sleep and wake-up (a few microseconds) and the holder is guaranteed to be running (its own CPU, preemption disabled: kernel code). Otherwise sleep. Adaptive locks spin briefly then sleep.
What are the four conditions for deadlock, and how do you prevent it in practice?
Mutual exclusion, hold and wait, no preemption, circular wait. In practice: a global lock order (break the circle), checked with tools such as lockdep or TSan; trylock with backoff; not holding locks across calls into unknown code.
Why must you wait on a condition variable in a while loop?
Mesa semantics: wake-up means "the condition may have changed", and other threads can run between the signal and your return from wait; spurious wake-ups are also allowed. Re-check under the mutex.
select, poll, epoll: what is the difference, and when would you use io_uring?
select and poll pass the whole interest list on every call and the kernel checks each entry: O(watched); select is also capped at descriptor 1023. epoll keeps the list in the kernel and a ready list filled by callbacks: O(ready). io_uring is a completion model with shared submission and completion rings: batch many operations per system call or none (SQPOLL); worth it for many small or truly asynchronous operations (disk I/O at high queue depth), and often disabled in containers for security.
Level-triggered vs edge-triggered epoll?
Level: reported on every wait while ready. Edge: reported once per new event; you must drain to EAGAIN. Edge avoids repeated reports and thundering herds with several waiters; level is harder to misuse.
Why does a Python I/O thread get slow when another thread computes?
It must re-take the GIL after its I/O completes; the computing thread releases it only when asked, after the 5 ms switch interval. Measured: a 2 ms sleep came back about 8 ms late next to one busy thread.
What changes in the free-threaded build, and what does not?
The GIL is gone: threads run Python in parallel. Built-in containers take internal locks so they never corrupt, reference counts are biased towards the owning thread, and some objects are immortal. What does not change: a read-modify-write on shared data (d[k] += 1) is still a race and needs a lock.
OSTEP reading map for this page (reference)
ChapterHere
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).