8.4 Mutexes

CONCURRENCYSTATUS: STABLELEVEL: INTERMEDIATEREVIEWED: 2026-11-15
Before this page Race Conditions

8.4.1 Motivation

When multiple threads run in the same memory space, they can interfere. A thread writing to a variable while another reads it can corrupt state. A scheduler queue that two threads pop from at once can deliver the same task to both. Threads need a way to grant exclusive access to a resource. That mechanism is a mutex.

8.4.2 The problem

Shared mutable state is the core problem. Consider a symbol table that maps names like x and sqrt to values. Thread A looks up a name while Thread B adds a new one. Without coordination, A can read a partially written entry. Or both threads can grab the last free slot in the table at once.

The solution is mutual exclusion: only one thread at a time can modify the table. A mutex is the lock that enforces this rule.

8.4.3 Mental model

Intuition

A mutex is like a protected room with one door. Only one worker can be inside at a time. Other workers wait outside. When the worker inside finishes and leaves, one of the waiting workers enters.

The door is the lock. Entering is called acquiring it. Leaving is releasing it.

Mechanics

Multiple threads compete to acquire a mutex. The winner enters the critical section, a block of code that accesses the protected resource. The losers wait.

When the winner releases the lock, the kernel wakes one of the waiting threads. That thread tries to acquire the lock again. It usually wins, but a thread that arrived in the meantime can take the lock first.

Runtime detail

Acquiring a mutex starts with an atomic operation called compare-and-swap. The thread reads the lock state (0 for unlocked) and tries to set it to 1 (locked) atomically. If the word still held 0, the swap succeeds and the thread owns the lock. The word “atomic” means no other thread can see the state between the read and the write.

If the lock was already held, compare-and-swap fails. The thread does not acquire it. The thread can now spin: it keeps checking the lock word in a tight loop and retries the compare-and-swap when it reads 0. Spinning wastes CPU time but is very fast if the lock holder releases soon.

If spinning does not get the lock within a bounded number of attempts, the thread calls into the kernel. The kernel checks that the lock word still holds the value the thread last saw, meaning the lock is still held, and if so parks the thread. The parked thread consumes no CPU. The kernel wakes it later when the lock is released.

Releasing the lock also requires care. The thread writes 0 to the lock word with an atomic exchange that has release ordering. The exchange also returns the old value, which says whether anyone is waiting. The release ordering means every write it made inside the critical section is visible to the next thread that acquires the lock. The lock operation has acquire ordering, so the next owner cannot read the protected data before it holds the lock. This pairing is memory ordering, and on CPUs that let stores become visible out of order, a lock depends on it as much as on mutual exclusion.

Finally, if the lock word records that threads are waiting, releasing the mutex also calls the kernel to wake one of them. The kernel makes no promise about which waiter wakes. The woken thread tries for the lock again, competing with any thread that arrived in the meantime.

8.4.4 Mechanism

Uncontended acquisition

The typical case has no contention. Thread A acquires the mutex, does its work, releases it, and moves on. The lock and the unlock are one atomic instruction each, with no system call. How long they take depends on where the lock’s cache line was last used. On 2013 server hardware, David, Guerraoui and Trigonakis <https://doi.org/10.1145/2517349.2522714> measured atomic operations at about 20 cycles while one core had the line to itself, about 120 once a second core used the same location, and 350 to 450 cycles to acquire a lock last held on another socket.

Contended acquisition and the fast path/slow path split

When the mutex is held, threads take two paths. The fast path is spinning: the thread keeps checking the lock word and retries when it reads 0. If the holder releases soon, the spinning thread gets the lock with no kernel call. While it spins, it burns CPU cycles that another thread could have used.

The slow path involves parking. If the lock is still held after a bounded number of spins, the thread calls the kernel. Rust’s standard library on Linux spins 100 times before it waits. glibc’s default pthread mutex does not spin at all: only the PTHREAD_MUTEX_ADAPTIVE_NP type does, up to 100 times unless the glibc.pthread.mutex_spin_count <https://sourceware.org/glibc/manual/latest/html_node/POSIX-Thread-Tunables.html> tunable changes it. The kernel records the parked thread in a queue and stops it. When the lock releases, the kernel wakes one parked thread, which then competes with any spinning threads. This path is slow to enter but has no wasted spins.

The kernel interface for this on Linux is the futex system call, which its manual page describes as “fast user-space locking”. The design keeps locking in user space when there is no contention and enters the kernel only when a thread must wait.

thread A thread B holds lock: critical section tries lock, spins parked in kernel wakes, acquires release wakes B

Thread B finds the lock held, spins, then parks in the kernel. A’s release wakes it, and B acquires the lock after a wake-up delay.

stateDiagram-v2
  direction LR
  state "Locked by A" as LockedA
  state "B spins" as Spin
  state "B parked" as Park
  state "Locked by B" as LockedB
  [*] --> Unlocked
  Unlocked --> LockedA : A acquires
  LockedA --> Spin : B arrives, lock busy
  Spin --> Park : spin budget exceeded
  Park --> Spin : A releases, wakes B
  LockedA --> Unlocked : A releases
  Spin --> LockedB : A releases, B acquires
  LockedB --> Unlocked : B releases

The same exchange as states. B spins until its spin budget runs out, then parks; A’s release wakes it, and B spins once more and takes the lock.

Contention and scaling

When many threads contend for one lock, scaling collapses. The critical section is serialized: only one thread enters at a time, however many cores the machine has. Once the threads spend most of their time waiting for that section, adding more threads adds no throughput, only spinning, parking and context switches. The lock becomes a bottleneck.

This is why lock granularity matters.

8.4.5 Lock granularity

A coarse-grained lock protects many resources under one mutex. A fine-grained lock protects one resource or one piece of a resource.

CPython’s default build uses a coarse-grained approach. The Global Interpreter Lock (GIL) is one mutex guarding almost all mutable state in the interpreter. Any Python thread that runs Python code must hold it. Even on a 64-core machine, only one core runs Python at a time. The benefit is simplicity, with little room for deadlock inside the interpreter. The cost is that compute-bound pure-Python code cannot use more than one core. Since 3.13, CPython also offers a free-threaded build without the GIL (PEP 703).

A fine-grained design locks individual objects or small regions. Each symbol in a symbol table gets its own lock (or a small group of symbols shares one lock). Thread A can look up one symbol while Thread B modifies another. Both threads run in parallel. The cost is complexity. More locks mean more deadlock risk, more state to track, and more acquisition overhead.

The choice depends on the workload and the tolerance for deadlock risk. If threads mostly read and contention is rare, locks are not a bottleneck and coarse-grained is fine. If threads write often but to different parts of the data, fine-grained locks let those writes proceed in parallel. If they all write the same item, no granularity helps.

8.4.6 Deadlock

Four conditions must all hold for deadlock to occur:

  1. Mutual exclusion. Only one thread can hold the resource.
  2. Hold and wait. A thread holds a resource and waits for another.
  3. No preemption. A thread cannot forcibly take a held resource.
  4. Circular wait. A cycle of threads exists where each waits for the next.

All four are necessary. Break any one and deadlock cannot occur.

The practical cure is lock ordering. Define a strict order for acquiring locks. Thread A acquires lock 1 then lock 2. Thread B also acquires lock 1 then lock 2. Never the reverse. This breaks circular wait.

Lock ordering is easy to state but hard to maintain in large systems. Every code path must follow the order. A library function can acquire locks that a caller does not expect. Over time, as code evolves, lock orders shift and deadlocks appear. Tools help: ThreadSanitizer reports lock-order inversions it sees at run time, and the Linux kernel checks its own lock order with lockdep. Beyond that, it comes down to discipline and code review.

8.4.7 Read-write locks

Some resources are read far more often than written. Take a lookup table that 100 threads read and one thread updates once a second. Under a plain mutex the readers also exclude each other, so they take turns even though none of them changes anything. This wastes parallelism.

A read-write lock allows multiple readers to hold the lock at once. Only one writer can hold it, and only if no readers hold it. The first reader acquires the lock. The second reader sees the lock is held by readers and acquires it as well. Both readers run in parallel. When a writer arrives, it must wait for all readers to leave.

Read-write locks are more complex than plain mutexes, and each one has to pick a policy. If new readers keep entering while a writer waits, the writer starves. glibc’s default read-write lock prefers readers and accepts that risk (pthread_rwlockattr_setkind_np(3) <https://man7.org/linux/man-pages/man3/pthread_rwlockattr_setkind_np.3.html>); other implementations make new readers wait behind a queued writer. Every reader also writes the lock’s shared reader count when it enters and leaves, so with short read sections that count becomes a contended cache line of its own. A read-write lock pays off when reads far outnumber writes and each read section is long enough for running them in parallel to beat that bookkeeping.

8.4.8 Rust semantics

In Rust, a Mutex owns the data it protects. The type signature is Mutex<T>. The T is the data inside. To access the data, a thread calls lock(), which acquires the mutex and returns a guard. The guard dereferences to T. While the guard exists, the thread has exclusive access to T. When the guard is dropped, the mutex is released. This is RAII (Resource Acquisition Is Initialization): the resource (the lock) is tied to an object lifetime.

If a thread panics while holding the guard, the guard’s destructor still runs. It releases the mutex. To flag that a panic occurred during critical-section access, Rust marks the mutex as poisoned. From then on, every call to lock() returns an error that still carries the guard, so the caller decides whether to recover the data with into_inner() or to fail. The mutex stays poisoned until someone calls clear_poison().

This is very different from C. In C, a mutex and its data are separate. A global pthread_mutex_t lock and a global int counter both exist. The programmer must remember to acquire lock before reading or writing counter. Forgetting is a data race. C also has no unwinding to release a lock when a function exits early: a longjmp past the unlock leaves the mutex locked, and R’s error() leaves C code by longjmp.

Rust’s design forces the programmer to keep the lock and data together. The compiler verifies that the data is accessed only after acquiring the guard. Data races cannot happen outside unsafe code. Deadlock is still possible, and so is a logic error that leaves the data inconsistent, which is what poisoning flags.

8.4.9 Where threaded R needs locks

threaded-r’s first answer is to stop sharing: the symbol table and the string cache became per-interpreter members (patch 0055), so they need no lock. Locks remain where state is shared on purpose or cannot be split yet.

Most parser state moved into the interpreter, but four variables that the bison-generated parser declares itself are still process globals, so a process-wide mutex surrounds the one call to yyparse() (patch 0065). The mutex is recursive, because a parse can trigger a garbage collection whose finalizer parses again on the same thread.

A process-wide cache of package .rdb files is shared by design, since package contents do not change once written. Its bookkeeping was a plain read-modify-write (icache = used++), so two interpreters could claim the same slot, and a lock now covers that bookkeeping. The lock never covers the file reads, because every read failure there calls error(), and a longjmp would skip the unlock.

Loading and attaching a namespace take a process-wide lock (patch 0101). It was added to mitigate a crash in concurrent library() calls; patches 0102 to 0104 later fixed the crash, and the lock stays as defense in depth.

A shared heap is one hypothesis. Right now, threaded-r uses separate heaps per interpreter. If a future version unifies the heaps to save memory or enable certain optimizations, the heap allocator needs synchronization. Lock-free allocators exist but are complex.

A lock per interpreter does not make legacy native package code safe. A package’s shared library loads once per process, so its static and global variables are process-wide, while a per-interpreter lock protects only that interpreter’s state. Two interpreters, each holding its own lock, can still enter the same package’s C code at once and race on its statics. Only a lock that every interpreter takes before entering that code serializes it, and that lock gives back the parallelism the design set out to gain.

8.4.10 Tradeoffs

Fast uncontended acquisition is easy. Handling contention requires deciding between spinning (wasting CPU) and parking (paying a kernel call). The balance depends on lock-hold time and contention patterns.

Coarse-grained locking is simple to reason about but limits parallelism. Fine-grained locking enables parallelism but raises deadlock risk and debugging difficulty.

Rust’s ownership-based approach makes data races impossible in safe code. C’s discipline-based approach is more flexible but requires care.

Further reading

  • std::sync::Mutex <https://doc.rust-lang.org/std/sync/struct.Mutex.html>, Rust standard library documentation, for guards and poisoning.
  • Ulrich Drepper, Futexes Are Tricky <https://www.akkadia.org/drepper/futex.pdf>, Red Hat, 2011. Builds a futex-based mutex in three steps, starting from one that looks right and is not.
  • futex(2) <https://man7.org/linux/man-pages/man2/futex.2.html> manual page, for the system call interface, and FUTEX_WAKE(2const) <https://man7.org/linux/man-pages/man2/FUTEX_WAKE.2const.html>, which says no guarantee is given about which waiters wake.
  • Linux kernel locking documentation <https://www.kernel.org/doc/html/latest/locking/index.html>, which covers spinlocks, mutexes and the lockdep validator at the kernel level.

Where this appears

  • threaded-r Multiple interpreters must coordinate access to the state they still share, such as the parser and the package lazy-load cache. The choice between coarse and fine-grained locking shapes whether legacy packages can run safely.
  • r-in-rust (rrs) rrs avoids this entirely. Each interpreter owns its state. No global mutexes exist by design.

Where to go next

Back to top