0%
Concurrency and Async Programming: Threads, Locks, Event Loops, and Backpressure
Foundations
Concurrency Patterns
Asynchronous I/O
Lock Free Data Structures
Lock free data structures let many threads operate on shared state without ever blocking on a lock. They promise that the system keeps making progress even if some threads are delayed, preempted or killed. This section defines the progress guarantees precisely, explains why they matter, and sets out the realistic costs and benefits, because lock free does not automatically mean faster.
Why avoid locks at all
A lock is a promise that only one thread runs a critical section at a time. That promise has a dark side: if the thread holding the lock stops, everyone waiting stops too. A thread can stop for many reasons that have nothing to do with the program logic. The scheduler can preempt it at the end of its time slice. It can take a page fault and wait for the disk. It can be descheduled because a higher priority thread became runnable, which leads to priority inversion, the problem that famously reset the Mars Pathfinder lander in 1997. In a signal handler or an interrupt handler, taking a lock that the interrupted code already holds deadlocks immediately. Lock free structures remove these hazards because no thread ever holds anything that others must wait for. A delayed thread delays only itself.
The other motivation is latency predictability. A lock that is usually uncontended can still produce rare long waits when its holder is preempted, and those waits appear in the tail latency of a service. Systems such as trading engines, audio processing, game engines and kernel paths that run with interrupts disabled care about the worst case far more than the average, and lock free and wait free designs bound the worst case in ways locks cannot.
The progress hierarchy
Progress guarantees form a hierarchy, from weakest to strongest. A blocking algorithm, one that uses locks, offers no guarantee: if one thread stops at the wrong place, others may wait forever. An obstruction free algorithm guarantees that any thread running in isolation, with all others paused, completes its operation in a bounded number of steps; contending threads may repeatedly abort each other, so it can livelock. A lock free algorithm guarantees that, among all running threads, at least one completes an operation in a bounded number of steps; the system as a whole always progresses, but an individual thread can starve. A wait free algorithm guarantees that every thread completes every operation in a bounded number of its own steps, regardless of the others; there is no starvation at all.
Most practical non blocking structures are lock free. Wait free structures exist for many problems, and Maurice Herlihy proved in 1991 that any object can be given a wait free implementation using compare and swap, but general wait free constructions are slow. Fast wait free algorithms, such as the Kogan and Petrank wait free queue, usually start with a lock free fast path and fall back to a helping scheme in which threads finish each other operations when contention is high.
Linearizability
Progress is half the story; the other half is what the operations mean. The standard correctness condition for concurrent objects is linearizability, defined by Herlihy and Wing in 1990. A history of operations is linearizable if each operation appears to take effect at a single instant, its linearization point, somewhere between its invocation and its response, and the resulting sequential order is legal for the object. For a lock free stack, the linearization point of a successful push is the CAS that installs the new top. Linearizability composes: a system of linearizable objects is itself linearizable, which lets designers reason about each structure separately. Weaker conditions such as sequential consistency of objects and quiescent consistency exist and allow faster implementations, but they surprise users, so most libraries promise linearizability.
Lock free is not automatically faster
Lock free structures often lose to good locks under realistic workloads. Each operation may perform several atomic instructions where a lock based version performs two, and atomic instructions on contended cache lines are expensive regardless of whether a lock is involved. A single shared head or tail pointer is a contention point exactly like a lock. Retry loops waste work under heavy contention. Memory reclamation adds overhead to every operation in languages without garbage collection. Benchmarks of concurrent queues routinely show a well implemented mutex protected queue competitive with or faster than a lock free queue at moderate thread counts. The advantages of lock free structures are robustness to preemption and predictable tail latency, more than raw throughput.
Priority inversion and real time constraints
Priority inversion deserves a closer look because it is the clearest case where locks fail and lock free structures succeed. A low priority thread takes a lock. A high priority thread then needs the same lock and blocks. A medium priority thread, which needs no lock at all, becomes runnable and preempts the low priority thread, because the scheduler always prefers higher priority. Now the high priority thread waits for the low priority thread, which waits for the medium priority thread, so the most important work in the system is delayed by unrelated work of lower importance, potentially for an unbounded time. On Mars Pathfinder, a high priority bus management task waited on a mutex held by a low priority meteorological task while a medium priority communications task ran, and a watchdog repeatedly reset the computer until engineers enabled priority inheritance remotely.
Priority inheritance, in which the lock holder temporarily runs at the priority of the highest waiter, and priority ceiling protocols mitigate the problem for locks, and real time operating systems and Linux PI futexes implement them. Lock free structures avoid it entirely, because there is no holder to boost. This is why audio engines, where a missed deadline produces an audible glitch, follow the rule that the real time audio thread must never take a lock, allocate memory or make a blocking system call, and communicate with the rest of the program only through lock free queues.
Signal handlers and interrupt contexts
A second class of contexts where locks are dangerous is code that can interrupt arbitrary other code. A Unix signal handler runs on the thread that received the signal, in the middle of whatever that thread was doing. If the handler takes a lock that the interrupted code already holds, the thread waits for itself forever. The same is true of kernel interrupt handlers and of code that runs inside memory allocators or profilers. POSIX defines a short list of async signal safe functions, and anything else, including printf and malloc, may deadlock in a handler. Lock free structures, and atomic flags in particular, are the standard way for such handlers to communicate with the rest of the program: the handler sets a flag or pushes to a lock free queue, and the main loop does the real work later.
Costs that are easy to underestimate
The engineering cost of lock free code is often larger than its runtime benefit. The correctness argument for even a simple structure requires reasoning about every interleaving of every operation, including memory ordering on weak hardware. Bugs are rare, nondeterministic and catastrophic, appearing as memory corruption far from their cause. Reviews take experts. Modifications that look small, such as adding a size counter or a second pointer, can invalidate the whole argument. A team should adopt lock free structures from libraries freely, but should treat writing a new one as a significant project with a verification plan, not an afternoon optimization.
Lock free structures guarantee that some thread always progresses, so a preempted or slow thread never stalls the others, which helps tail latency and makes them safe in interrupt and real time contexts. They are not automatically faster: contended atomics on a shared head cost as much as a lock. Measure before replacing a lock.