0%
Concurrency and Async Programming: Threads, Locks, Event Loops, and Backpressure
Foundations
Concurrency Patterns
Asynchronous I/O
Mutexes and Critical Sections
A mutex, short for mutual exclusion lock, is the most widely used synchronization primitive. It lets a thread mark a region of code, the critical section, so that at most one thread executes any critical section guarded by the same mutex at a time. That one sentence hides three separate guarantees, mutual exclusion, memory visibility and progress, and good use of mutexes depends on understanding all three. This section explains what a mutex promises, what it does not, and the vocabulary used throughout the rest of the course.
Mutual exclusion
The first guarantee is the obvious one. A thread calls lock, executes the critical section, and calls unlock. If another thread calls lock on the same mutex while the first one holds it, the second thread waits until the mutex is released. Two critical sections guarded by the same mutex therefore never overlap in time. This turns any sequence of operations inside the critical section into one atomic step from the point of view of other threads that also use the mutex. The lost update disappears, because the read, the add and the write of the counter now happen as one indivisible unit.
The guarantee holds only among threads that use the same mutex. A mutex does not protect data; it protects code paths that agree to take it. If one path reads the balance under the account lock while another path updates it without the lock, the mutex provides no protection at all to the second path. This is why the association between a mutex and the data it guards must be clear and consistently respected, ideally enforced by encapsulation so that the data is reachable only through methods that take the lock.
Visibility
The second guarantee is memory visibility. As the previous lesson explained, unlocking a mutex is a release operation and locking it is an acquire operation. Everything a thread wrote while holding the lock, or before it, happens before everything the next thread that acquires the lock does after acquiring it. This is why a value updated inside a critical section is reliably seen by the next thread that enters, without any volatile or atomic declarations on the data itself. It also means that reading shared data without the lock gives up this guarantee, even if every write is done under the lock: the reader may see stale values, or values from the middle of an update that touched several fields.
Progress
The third guarantee concerns progress. A correct mutex is deadlock free in the sense that if the lock is free and threads are trying to take it, one of them will succeed. Most mutexes do not promise more. In particular, they usually do not promise fairness: a thread that has been waiting a long time is not guaranteed to get the lock before a thread that just arrived. Under heavy contention, a thread may in principle wait indefinitely while others repeatedly take the lock, which is called starvation. Some mutexes provide a fair mode that hands the lock to waiters in arrival order, at a significant cost in throughput, discussed later in this lesson.
Progress also depends on the code inside the critical section. If a thread holding the lock blocks forever, crashes without releasing it, or waits for another lock held by a thread that waits for this one, every thread that needs the lock stops. The mutex itself cannot fix these problems; disciplined critical section design, covered in a later section, and the deadlock techniques in a later lesson are what keep programs moving.
Ownership
A mutex has an owner: the thread that locked it. Most implementations require that the same thread unlocks it, and unlocking from a different thread is undefined behavior in C++ and Rust, and throws an IllegalMonitorStateException for Java monitors. Some debug builds check ownership and report errors. Ownership is what distinguishes a mutex from a binary semaphore, which can be released by any thread. Ownership enables useful features such as priority inheritance and reentrancy, and it makes errors easier to diagnose, because a deadlock report can name which thread holds which lock.
Scoped locking
The most common mutex bug in practice is forgetting to unlock, typically on an early return or an exception path. Every modern language provides a scoped form that releases the lock automatically when the scope ends: std::lock_guard and std::scoped_lock in C++, synchronized blocks and try finally with Lock in Java, with statements in Python, defer mu.Unlock right after mu.Lock in Go, and the guard object returned by Mutex::lock in Rust, which unlocks when dropped. Rust goes further by putting the protected data inside the mutex, so the only way to access it is through the guard, making it impossible to touch the data without holding the lock.
Choosing what a mutex guards
A recurring design question is how to decide which data belongs to which mutex. The guiding rule is that variables that participate in the same invariant must share a lock, and variables that never participate in the same invariant may have separate locks. A bank account has a balance and a list of recent transactions; if the invariant says the balance equals the sum of the transactions, both must be guarded by the same lock. The account also has a display name that changes independently; it can have its own lock, or simply share the account lock if contention is low, since sharing a lock is never incorrect, only potentially slower. When in doubt, err on the side of fewer locks guarding more data, because a missing lock is a correctness bug while an extra lock acquisition is only a performance cost that measurements can later reveal.
Locks across process boundaries
Mutexes normally coordinate threads within one process. Coordinating separate processes requires shared mechanisms such as a mutex placed in shared memory with the process shared attribute, a file lock with flock or fcntl, a named semaphore, or a database row lock. These add a new failure mode: a process may crash while holding the lock. Robust mutexes on Linux report to the next locker that the previous owner died, letting it repair the protected state; file locks are released automatically by the kernel when the process exits. Distributed locks across machines are harder still, because a holder can pause, for example during a long garbage collection, and lose its lease without knowing it, so writes guarded by a distributed lock should also carry a fencing token that the storage system checks. The principles of this lesson still apply: identify the invariant, hold the lock for the minimum time, and plan for the holder failing.
How to tell if you need a mutex
A quick test helps decide. Is the data accessed by more than one thread? Does at least one thread write it after other threads can see it? If both answers are yes, you need synchronization. If the data is a single word that does not guard other data, an atomic may suffice. If several values must stay consistent with each other, or an operation reads, decides and writes, you need a mutex or an equivalent such as an actor that owns the data.
A mutex gives mutual exclusion among threads that use it, release and acquire visibility for data touched in critical sections, and basic progress but usually not fairness. It protects code paths, not data, so tie each mutex to the data it guards, access that data only while holding it, and always use the scoped form of locking.