Search

Search papers and lessons

Wait-Free Synchronization

Level 4 · 12 min read

A wait-free operation finishes in a bounded number of its own steps, however slowly other threads run or even if they stop, which is the strongest progress guarantee for shared data.

On this page

  • Colour = topic mix
  • Systems
  • Discrete math
  • Distributed systems
  • Networking
  • Programming languages
  • ReadReady to readNot yet

TL;DR

A linearizable shared object is safe to use from several threads, but safety says nothing about how long a call takes. A wait-free object guarantees that every operation finishes in a bounded number of its own steps, no matter how slowly the other threads run, and even if some of them stop forever. This matters because a lock held by a paused thread blocks everyone else, and a retry loop can make one thread lose again and again.

Builds on: Linearizability, Mutual Exclusion, Thread, Compare-and-Swap · Leads to: the bivalence argument, which shows that some objects cannot be wait-free

Where it's used

Real-time audio. A sound card asks for the next block of samples at a fixed rate. A block of 512 samples at 48,000 samples per second is due every 512 / 48,000 seconds, about 10.7 milliseconds. If the audio thread waits on a lock that a lower-priority thread holds, and that thread gets paused by the operating system, the audio glitches. Audio engines therefore pass samples through lock-free or wait-free ring buffers.

Interrupt handlers and kernel code. An interrupt handler in the Operating System runs on top of whatever code was interrupted. If that code holds a lock, the handler cannot wait for it, because the lock holder cannot run until the handler returns. Shared state touched in interrupt context has to be updated without blocking, which is a wait-free or lock-free requirement.

Atomic counters in standard libraries. The java.util.concurrent.atomic package and C++'s std::atomic give programmers single shared values, such as counters and flags, that many threads can update without a mutex. A counter whose increment is one hardware instruction is wait-free, since the instruction completes in one step.

How it works

We will use one shared counter c, which starts at 0, and see what each design guarantees when several threads add 1 to it.

  1. The lock-based version. A thread takes the lock, reads c, writes c + 1, and releases the lock. The other threads wait at the lock. Check: if the lock holder is paused for one second, every other thread makes no progress during that second. Its number of steps is not bounded by anything the waiting thread controls.

  2. The compare-and-swap idea. Hardware offers an instruction CAS(c, e, v): it writes v into c only if c still holds the expected value e, and it reports whether it wrote. A thread can increment without a lock: read c to get e, compute e + 1, then CAS(c, e, e + 1). Check: if c was 0 and the CAS was called with e = 0, the write happens and the CAS reports success.

  3. The retry loop. When two threads both read 0 in a race, the first CAS succeeds and the second one fails, because c is now 1 and not 0. The loser reads again and tries again. Check: the loser's CAS fails exactly when another thread's write got in between its read and its CAS.

  4. Why the retry loop is not wait-free. Nothing limits how many times the loser can fail. If the other thread keeps finishing its increments between this thread's read and CAS, this thread never succeeds. The system as a whole still makes progress, because someone's CAS keeps succeeding, but this one thread has no bound on its steps. Check: a loop that fails three times in a row has taken three CAS steps and still has not finished.

  5. The one-step version. Some hardware offers a fetch-and-add instruction, which adds a value to c and returns the old value, all in one indivisible step. Each thread calls it once. Check: three calls on a counter at 0 return 0, 1 and 2 in some order, and leave c at 3. Each call is a single step.

  6. Naming the guarantees. An operation is wait-free if its thread finishes within a fixed number of its own steps. It is lock-free if, whatever the schedule, some operation always finishes. It is obstruction-free if an operation finishes when its thread runs alone. Wait-free implies lock-free, and lock-free implies obstruction-free. Check: the retry loop in step 3 is lock-free but not wait-free.

flowchart TD
  A["Read the current value"] --> B["Compute the new value"]
  B --> C["Try compare-and-swap: write only if still unchanged"]
  C -- "succeeded" --> D["Done"]
  C -- "failed, someone else wrote first" --> A

The math

A shared object is a data structure that several threads call through operations. An execution is a sequence of steps, each step taken by one thread. A thread's own steps are the steps in the execution that that thread takes.

Definition: Wait-free
An object is wait-free when, for every operation, there is a bound BB such that in every execution, if thread ii has taken BB steps inside that operation, the operation has returned. The bound may depend on the operation and on the number of threads, but not on how the other threads are scheduled, and a thread may stop at any point without affecting the bound.

Step 1 in symbols: the lock-based bound

With a lock, a waiting thread's step count is not bounded by BB, because its steps are spent in a loop waiting for the lock holder. Write wiw_i for the number of steps thread ii spends waiting. If the lock holder is paused, wiw_i can grow without limit, so the object is not wait-free. A blocking object is one where a stopped thread can stop everyone else.

Step 2 in symbols: the CAS primitive

CAS(c,e,v)=if c=e then c←v and return trueotherwise return false\mathrm{CAS}(c, e, v) = \begin{aligned} &\text{if } c = e \text{ then } c \leftarrow v \text{ and return true} \\ &\text{otherwise return false} \end{aligned}

A CAS-based increment repeats two steps, a read and a CAS, until the CAS returns true. Each failed CAS means some other thread's write changed the value, so the system as a whole made progress.

Step 3 in symbols: the progress hierarchy

Let the execution be infinite.

  • Lock-free: infinitely many operations return.
  • Wait-free: each operation returns after at most BB of its thread's steps.

A wait-free object is lock-free. The converse is false: the retry loop has infinitely many completions overall, but a single thread can fail forever.

Step 4 in symbols: consensus numbers

Each thread proposes a value. A wait-free consensus protocol for nn threads requires that every thread returns the same value, that this value was proposed by some thread, and that every thread returns after a bounded number of its own steps. The consensus number cn(X)\mathrm{cn}(X) of a primitive XX is the largest nn for which XX together with ordinary read/write registers can solve wait-free consensus for nn threads.

  • Read/write registers: cn=1\mathrm{cn} = 1.
  • Fetch-and-add: cn=2\mathrm{cn} = 2.
  • Compare-and-swap: cn=∞\mathrm{cn} = \infty.

A primitive with a consensus number of nn cannot build a wait-free object that needs n+1n+1 threads to agree.

Worked examples

Example
1. Three threads, one fetch-and-add

Shared counter c=0c = 0. Threads T1T_1, T2T_2, T3T_3 each call fetch-and-add with 1 once.

  1. T1T_1 runs its single step: it receives the old value 0 and sets c=1c = 1.
  2. T2T_2 runs its single step: it receives 1 and sets c=2c = 2.
  3. T3T_3 runs its single step: it receives 2 and sets c=3c = 3.
  4. Each thread took exactly one step, so each operation is wait-free with B=1B = 1.
  5. The three returned values are 0, 1 and 2, which are distinct, and the final value is 3.

Interpretation: a single hardware instruction gives a wait-free counter, and every thread gets a different ticket number no matter the schedule.

Example
2. Two threads, one CAS retry

Shared counter c=0c = 0. Threads AA and BB each want to add 1 with a CAS loop. Count only each thread's own steps.

  1. AA reads cc and gets eA=0e_A = 0. This is AA's step 1.
  2. BB reads cc and gets eB=0e_B = 0. This is BB's step 1.
  3. AA calls CAS(c,0,1)\mathrm{CAS}(c, 0, 1). Since c=0c = 0, the write happens and c=1c = 1. AA returns after its second step.
  4. BB calls CAS(c,0,1)\mathrm{CAS}(c, 0, 1). Since c=1≠0c = 1 \neq 0, nothing is written, and the CAS returns false. This is BB's second step.
  5. BB reads cc again and gets 1. This is BB's third step.
  6. BB calls CAS(c,1,2)\mathrm{CAS}(c, 1, 2). Since c=1c = 1, the write happens and c=2c = 2. This is BB's fourth step, and BB returns.
  7. Final value c=2c = 2. BB used 4 steps, and AA used 2.

Interpretation: BB's cost grew from 2 steps to 4 because AA got in first. If AA had kept winning every round, BB's count would have no upper bound, so this loop is lock-free but not wait-free.

Try it: in example 2, suppose AA wins every round, so each time BB tries its CAS, cc has already changed. How many steps does BB need before it returns? Answer: there is no fixed number. Each round costs BB two more steps and still ends in failure, so BB's count is unbounded, which is exactly why this loop is not wait-free.

Example
3. A realistic audio ring buffer

An audio producer writes samples into a ring buffer of N=8N = 8 slots, and the audio callback reads them. The writer's index ww and the reader's index rr both count modulo 8. Keep one slot empty to tell "full" from "empty", so the usable capacity is N−1=7N - 1 = 7. Here w=2w = 2 and r=5r = 5.

  1. The number of stored samples is (w−r) mod N=(2−5) mod 8(w - r) \bmod N = (2 - 5) \bmod 8.
  2. 2−5=−32 - 5 = -3, and −3 mod 8=5-3 \bmod 8 = 5 (add 8 to get 5).
  3. So 5 samples are stored, and the writer can add 7−5=27 - 5 = 2 more before the buffer is full.
  4. A write reads rr, checks for space, writes one slot, and moves ww forward. A read does the same in reverse. Each is a fixed number of loads and stores with no loop and no lock, so each is wait-free for one producer and one consumer.
  5. Compare with the deadline: a 512-sample block at 48,000 samples per second is due every 10.7 milliseconds. A wait-free operation adds a bounded delay, so the callback can meet that deadline even if the producer thread is descheduled.

Interpretation: the buffer's arithmetic is trivial, but the property that matters is that neither side waits for the other.

Try it: with N=8N = 8, w=6w = 6 and r=1r = 1, how many samples are stored, and how many more can the writer add? Answer: (6−1) mod 8=5(6 - 1) \bmod 8 = 5 samples are stored, and the writer can add 7−5=27 - 5 = 2 more.

Common mistakes and tradeoffs

It is tempting to think that "lock-free" means "has no locks." In fact it is a progress guarantee: some operation always finishes, whether or not a lock appears in the code. A lock-free design can still use memory barriers and retry loops, and a design with no visible lock can still block if one thread waits on another. The guarantee is what matters, not the mechanism.

It is tempting to think that a CAS loop is wait-free because it usually succeeds on the first try. In fact the guarantee is about the worst case. Under heavy contention a retry loop can fail for a long time, and a lock-free algorithm bounds the system's progress, not any one thread's.

It is tempting to think that wait-free means "never retries." In fact a wait-free algorithm may retry, provided each thread's retries are bounded. Many wait-free constructions use "helping," where a thread that succeeds finishes the pending operations of threads that have not, which bounds how long any one thread can be delayed.

When to use it. Choose wait-free designs when a thread has a deadline or when a thread may be interrupted, paused or killed while it holds shared state: audio, interrupt handlers, real-time control, and recovery code.

When not to use it. For ordinary server code with low contention, a plain mutex is usually simpler, easier to reason about and faster. Wait-free constructions are often hard to get right, use more memory, and can be slower on average.

Alternatives. Keep critical sections short with a lock, use lock-free data structures where a retry loop is acceptable, or use read-copy-update for data that is read far more often than it is written.

History

Programmers wrote lock-free and blocking shared structures case by case for decades, with no common vocabulary for what each one guaranteed. In 1991 Maurice Herlihy formalised wait-freedom and introduced consensus numbers, which rank synchronization primitives by how many threads they can coordinate. The ranking showed that registers alone cannot solve consensus even for two threads, while compare-and-swap can handle any number of threads. Herlihy also showed that CAS can build a wait-free version of any object, a result that became known as universality and is closely related to State Machine Replication. The idea caught on because it turned a vague goal into a measurable one and told hardware designers which primitives were worth building.

Recap

  • A shared object is safe when its operations are linearizable, but safety does not bound how long an operation takes.
  • A lock lets a paused thread block everyone, and a CAS retry loop lets one thread lose forever.
  • Wait-free means each operation finishes within a bound on its own steps. Lock-free means the system always makes progress. Wait-free implies lock-free.
  • Consensus numbers rank primitives: registers have 1, fetch-and-add 2, and compare-and-swap is unbounded.
  • Next, read Bivalence, which uses the same state-based reasoning to show that some tasks cannot be solved in certain settings.

Check yourself

QuestionTwo threads run a CAS-based increment on a counter that starts at 0. Thread A's CAS succeeds first. Why does thread B's CAS fail, and what does B do next?Show answer
B's CAS was issued with expected value 0, but A's write changed the counter to 1, so the comparison fails and nothing is written. B must read the counter again, get 1, and retry with expected value 1.
QuestionA fetch-and-add operation runs on a counter at 4. What value does the operation return, and what is the counter after it?Show answer
It returns the old value 4 and the counter becomes 5. The call is a single step, so it is wait-free with bound 1.
QuestionWhy is a CAS retry loop lock-free but not wait-free?Show answer
Lock-free means that across the whole system some operation always finishes, and each failed CAS means another thread's write succeeded. Wait-free requires a bound on one thread's own steps, and a thread can fail its CAS indefinitely if other threads keep winning, so no such bound exists.
QuestionA ring buffer has 8 slots, with one kept empty. The writer index is 0 and the reader index is 3. How many samples are stored, and how many more can be written?Show answer
Stored samples are (0−3) mod 8=5(0 - 3) \bmod 8 = 5. The usable capacity is 7, so 2 more can be written.

Sources