Skip to main content

Lesson 14 of 26 · 11 min read

Building locks: from spin-locks to sleeping futexes

Compare hardware atomic primitives (Test-and-Set, Compare-and-Swap, LL/SC, Fetch-and-Add) and see how OS wait queues eliminate wasted spinning.

Four lock implementations: Test-And-Set, Ticket lock, Park and queue, and Linux futex.
Real mutex locks pair hardware atomic primitives with OS wait queues so contended waiters sleep instead of burning CPU.
Course syllabus · lesson 14 of 26
In this lesson

A mutex makes a critical section appear indivisible to other threads that use the same mutex. The mutex itself has shared state, so contenders need an indivisible way to claim it. Once a contender discovers that someone else owns the lock, it has a second problem: how to wait without consuming a time slice or missing the release that would let it continue.

Lock evolution from Test-And-Set spin-locks to Fetch-And-Add ticket locks, Park/Unpark sleeping queues with guard spinlock, and two-phase Linux futexes.
Open full-size diagram
Good locks require both hardware atomicity (so lock acquisition cannot race) and OS wait queues (so waiters do not burn full time slices spinning).

Follow an uncontended lock into a futex wait

Thread A acquire, Thread B ready, Lock word held by A, Wait queue emptyThread AacquireThread BreadyLock wordheld by AWait queueempty

Step 1 of 4

Acquire in user space

A uses an atomic instruction to acquire the available lock. The uncontended fast path needs no system call.

Separate safety, progress, and cost

Mutual exclusion means at most one thread owns the lock at any time. Progress concerns who eventually acquires it. A lock may let some thread proceed after each release while repeatedly passing over a particular waiter. Fairness typically restricts that behavior, for example by serving requests in ticket order. Finally, performance depends on the common case: an uncontended acquire and release, a short wait on another core, or a long wait for an owner that has been descheduled.

Suppose a lock is represented by a flag, with zero meaning free and one meaning held. A program that loads the flag, checks for zero, and then stores one fails even if each individual access is atomic. A can load zero, B can load zero, then both can store one and enter. Making the store visible sooner would leave the check and claim as two operations. Disabling local interrupts can protect certain short kernel regions against interruption on a single CPU. A second CPU can still access the flag, and user-space mutexes need an acquisition protocol that works across cores.

Atomic claims and memory ordering

On x86 an xchg with a memory operand atomically exchanges the register and memory values and has implicit locking semantics. With one in the register, the instruction writes one to the lock word and returns the old word in the register. Only the thread that gets zero owns the lock. Another contender gets one and retries. An exchange loop is easy to verify because between any two successful exchanges there must be a release that writes zero. Each failed exchange also writes one, which can move the cache line between cores. A test-and-test-and-set loop first observes the lock with ordinary atomic reads and tries the exchange when the word appears free. The exchange must still decide the winner.

Code exampleAssembly
retry:
    movl $1, %eax
    xchgl %eax, flag(%rip)
    testl %eax, %eax
    jnz retry

Starting at zero, A's exchange returns zero and leaves one in memory, so A falls through. B's exchange returns one and leaves one in memory, so B branches back to retry. Restoring the one in the register at the start of each attempt defines the desired value independently of what the previous exchange returned.

Compare-and-swap changes memory only when it matches an expected value. In x86 lock cmpxchg on a memory operand, the accumulator supplies the expected value and a register supplies the replacement. On success the processor sets the zero flag and stores the replacement. On failure it clears the zero flag and loads the observed value into the accumulator. For an acquisition with expected zero and desired one, code that retries must remember to reset the expected value to zero after failure. Otherwise the next attempt might compare against one and mistake matching a held lock for successfully claiming a free one. The same issue arises in C with compare-exchange APIs that update an expected-value argument.

Load-linked and store-conditional split the protocol differently. An LL reads a word and establishes a reservation. The thread checks the loaded value. If it was zero, the corresponding SC tries to write one while that reservation remains valid. An intervening conflicting store invalidates the reservation. Depending on the architecture it can also be lost for other reasons, so SC failure means retry from LL. For example, A and B both load-link zero. A's conditional store succeeds, invalidating B's reservation. B's conditional store fails and its next linked load can observe one. Some instruction sets use different names and return conventions for the same pattern.

In a portable implementation the lock word is atomic. A successful acquisition needs acquire ordering and unlock needs release ordering. These operations make the previous owner's writes to protected data visible to the new owner. Polling loads before the acquisition can often be relaxed because seeing a free flag does not give permission to touch the data. Analysing ownership and memory visibility separately helps explain why an algorithm with the right state transitions can still be incorrect if implemented with plain C accesses or the wrong barriers.

Ticket locks and the cost of waiting in line

A ticket lock uses two atomic counters, next and turn, both initially zero. Fetch-and-add on next returns a unique old value to each arrival. The caller spins on turn until its number matches. The owner releases with an ordered increment of turn. Reads of turn that grant entry have acquire ordering. With bounded counters, the implementation needs a wraparound representation and a bound on outstanding tickets so live requests never share a ticket number.

If A, B, and C receive zero, one, and two, advancing turn to one admits B only. This is FIFO in the order of ticket allocation, independent of which waiter checks the counter fastest. Eventual entry still depends on the owner releasing and every earlier ticket holder being scheduled. If B is descheduled when its turn arrives, C waits even if a core is available. Many waiters also read the same cache line, so each change to turn can trigger work across several caches.

Spinning pays off when the owner is running on another core and will release sooner than the cost of sleeping and waking. On one core a waiter that gets a 10 ms time slice while the owner is preempted can waste the whole slice. Yielding can shorten the waste, but it depends on whom the scheduler picks and can lead to repeated scheduling of threads that still cannot acquire the lock. A blocking mutex gives the scheduler explicit information that a waiter has no useful work until a release.

Queueing and the Solaris wakeup race

OSTEP's Solaris example separates a short guard spin lock from the lock's ownership flag. The guard protects the flag and a queue of waiting thread IDs. An uncontended caller sets the ownership flag and releases the guard. A contending caller enqueues, announces its intention to sleep using setpark(), releases the guard, and calls park(). Whoever unlocks next also takes the guard. With no waiters it clears the flag. With a waiter it removes the queue head and calls unpark(thread_id). The flag stays set because ownership is being handed directly to that waiter. A newcomer racing with the handoff sees a held lock and queues behind it.

There are two places where moving a line changes the algorithm. If a waiter calls park() while holding the guard, the owner cannot take the guard to perform the handoff. If a waiter releases the guard before calling setpark(), the owner can perform the handoff too early. Solaris's intended protocol allows an unpark() arriving after setpark() to make the next park() return immediately. The announcement occurs under the guard, so a releasing owner cannot dequeue the waiter before this protection is set up.

The guard itself can involve spinning if its temporary owner is preempted. Keep the work under it small relative to the section that the main lock protects. The queue and wakeup calls are part of a larger protocol. A real implementation must account for interrupted waits and ensure that only the chosen recipient proceeds, with the necessary release and acquire ordering on handoff.

Linux futexes and conditional sleep

A Linux futex pairs a 32-bit user-space word with kernel wait operations. The interface gives the thread library a building block for a mutex. The encoding of free, held, and possible waiters is a library choice. An uncontended acquire can use a compare-exchange in user space, and an uncontended release can publish a free state in user space. This keeps system calls off the fast path.

A waiter bit can conservatively say that someone might be asleep. A wake that finds nobody costs a system call. Clearing the bit while a sleeper still depends on it can cost progress. The state machine therefore has to account for the entire path from a failed fast-path attempt through sleeping, waking, and the eventual release by the next owner.

In a conceptual encoding, zero is free, one means held with no known waiters, and two means held with possible waiters. A contender has to record contention atomically before waiting so that the releasing thread knows it may have to wake somebody. A representative slow-path exchange places two in the word. If it observed zero, the contender just acquired the lock in contended state. If it observed a held state, it tries FUTEX_WAIT with expected value two. Unlock publishes zero with release ordering and calls FUTEX_WAKE when the prior state indicates possible waiters. A woken thread retries acquisition with the slow-path protocol, which preserves wakeups for other sleepers when that thread later releases.

The key operation is the kernel's atomic compare-and-block with respect to futex operations on that word. If the owner changes two to zero before the waiter reaches the kernel, the mismatch lets the waiter return without sleeping. If the waiter has already queued, the wake can find it. If another contender acquired in between and the word is two again, the new owner is responsible for the next wake. Waking makes a thread runnable. It must recheck or retry on return, since wakeup can occur without ownership and others may acquire first. Some mutexes add bounded spinning before entering this slow path to catch very short holds.

Worked trace

Use one core, a 10 ms quantum, and an owner with 1 ms left in its critical section. A was near the end of its time slice when it acquired the lock, so the timer can preempt it soon after acquisition.

Code exampleTrace
Time from preemption   A                              B
0 ms                   Runnable, owns the lock        Starts running
0 to 10 ms             Cannot execute its unlock      Repeats failed exchanges
10 to 11 ms            Resumes and releases           Runnable again

The lock stayed safe throughout. The CPU spent 10 ms testing a state that the scheduled thread could never change. With a blocking mutex, B instead marks contention and tries to wait. If A runs immediately after B blocks, it can release roughly 1 ms later plus synchronization and scheduling overhead. With a ticket lock, B could have the next number and still waste the slice spinning. Ordered admission and efficient suspension solve different problems.

Now trace a futex release between B's contention mark and its kernel wait. Begin with A holding state one. B exchanges in two and observes one. A exchanges in zero and issues a wake that finds no sleepers. B finally calls wait with expected two. The kernel sees zero and B retries without sleeping. If B had entered the kernel first, the wake would instead have marked it runnable. Both schedules rely on the word changing before the wake.

Change one input

Keep the same gap before the wait, but replace the futex protocol with the Solaris handoff and omit setpark(). B joins the queue and drops the guard. A takes the guard, removes B, leaves the ownership flag set, and issues unpark(B) before B actually parks. In the teaching protocol without an announced park, that wake can be lost. B can now sleep with A gone and the lock reserved for B. Adding setpark() inside the guard closes precisely that window. Lesson 15 puts these locks to work in concurrent data structures.

Before you move on

Try it in your workspace

Compare test-and-set spin-locking, compare-and-swap, ticket locks via fetch-and-add, and futex wait/wake queues. Explain why spin locks hurt a single-CPU VM while futexes avoid wasting ticks.

Keep a short note of what you tried, what passed, and what you still need to check.

Your practice record

0 of 3 checked.

Saved in this browser when storage is available. Uncheck any item to revisit it. This is your own record, not an assessment.