Section 9.7

Spinlock

Definition

A spinlock is a lock whose waiters spin: a thread that finds the lock taken tests it repeatedly in a loop, keeping its processor core busy, until the lock is free. Like any lock, it lets one thread (one of several instruction sequences sharing memory) at a time run a critical section §9.4, code that uses shared data. A mutex §9.5 instead puts waiters to sleep. Spinlocks suit short critical sections that never sleep, and only where no code that takes the same lock can suspend the holder on the holder’s core.

The idea

Some code needs a lock but must not sleep. An interrupt handler §6.12, the routine a processor runs when a device signals an event, runs on top of the code it suspended and has no thread of its own that a scheduler could put to sleep. Other code could sleep but should not: if the lock will be free in 1 microsecond, going to sleep and being woken costs more than the wait. On several cores, the cheapest way to wait for a short critical section running on another core is to keep testing the lock.

The picture is a person outside a single-occupancy room who tries the door handle every second, which costs little while the occupant will leave soon. The picture stops being accurate on a single core. There the waiter and the holder take turns on the same core, so while the waiter keeps trying the handle, the holder is frozen and cannot leave. Every correct use of a spinlock rules that case out.

How it works

The simplest spinlock is one shared memory word, the lock word, that holds 0 when the lock is free and 1 when a thread holds it.

  1. Acquire. The thread performs an atomic operation §9.8 called exchange, or test-and-set: one indivisible step that writes 1 to the lock word and returns the value it replaced. If the returned value is 0, the lock was free and the thread now holds it. If it is 1, another thread holds the lock, and the thread tries again.

  2. Wait cheaply. Every exchange is a write. Each core keeps copies of recently used memory in its cache, a small fast memory, in blocks called cache lines, and each write takes the cache line holding the lock word away from every other core. A common refinement, test-and-test-and-set, spins on atomic reads until the lock word reads 0, and only then retries the exchange. Processors offer hint instructions for such loops, such as PAUSE on x86 processors.

  3. Run the critical section. The holder runs the protected code, which must not sleep or wait for any other event.

  4. Release. The holder writes 0 to the lock word.

The exchange and the releasing write also order memory accesses. The exchange uses acquire order and the release uses release order, the pair that the acquire-release ordering §9.11 entry describes. Together they keep the accesses of the critical section between acquisition and release, whatever reordering the compiler or the processor would otherwise do, and they make every write of one critical section visible to the next holder. In C11, the 2011 edition of the C standard, a minimal spinlock on a variable lock of type atomic_flag acquires with

while (atomic_flag_test_and_set_explicit(&lock,
memory_order_acquire)) { }

and releases with atomic_flag_clear_explicit(&lock, memory_order_release).

That loop gives mutual exclusion, but nothing in it ensures that the holder can reach its release. Operating system kernels therefore add rules about where the lock may be taken. In the Linux kernel, spin_lock disables preemption on the local core: the scheduler may no longer suspend the holder to run another thread. spin_lock_irqsave also disables interrupts §6.11 on the local core and saves their previous state, which spin_unlock_irqrestore puts back. A lock that an interrupt handler also takes must be taken with interrupts disabled by all other code. The Zephyr real-time operating system’s §6.33 k_spin_lock always masks interrupts on the local core, that is, holds them pending. In a kernel built for one core, these functions do no spinning at all: disabling preemption or interrupts is the entire protection.

A test-and-set lock is unfair. After a release, whichever waiting core wins the next exchange gets the lock, so one waiter can lose every time, which is called starvation §9.18. A ticket lock serves waiters in arrival order, first in, first out §14.14 (FIFO). It keeps two counters, next and serving, both starting at 0. A thread takes a ticket with an atomic fetch-and-add on next, which returns the old value and adds 1, and spins until serving equals its ticket. Release adds 1 to serving.

Worked example

The numbers are invented but of realistic size. Going to sleep and being woken costs a thread two context switches, each of which saves one thread’s registers and loads another’s, at 5 microseconds each: 10 microseconds in all. The critical section lasts at most 2 microseconds.

Two cores. Thread A on core 0 takes the lock at time 0 and releases it at 2 microseconds. Thread B on core 1 tries at 0.5 microseconds, finds the lock taken, and spins. B gets the lock just after 2 microseconds, having spun for 2−0.5=1.52 - 0.5 = 1.5 microseconds. Sleeping would have cost B at least 10 microseconds of switching. Spinning is the better choice whenever the expected wait is shorter than the cost of sleeping and waking.

One core, an interrupt handler. Thread A holds the lock and is 1.2 microseconds into its 2-microsecond critical section when an interrupt arrives. The interrupt handler tries to take the same lock and spins. Thread A cannot run until the handler returns, and the handler cannot return until A releases the lock, so the core spins forever. This is a deadlock §9.14, a state in which each party waits for the other, built from one thread and one handler on one core. Had A taken the lock with spin_lock_irqsave, the interrupt would have stayed pending. A would have finished its remaining 2−1.2=0.82 - 1.2 = 0.8 microseconds and released the lock, which re-enables interrupts. The handler would then have run and taken the free lock at once. The price is an interrupt served 0.8 microseconds late.

One core, two threads. A spinlock written by hand with an atomic flag in an ordinary program cannot disable preemption. Threads A and B have equal priority, and the scheduler gives each a time slice of 10 ms in turn. A’s slice ends 1 microsecond before A would have released the lock. B then spins for its whole slice of 10 ms, which is 10,000 microseconds, with no chance of success, before A runs again and releases the lock. If B instead had higher priority than A, under preemptive scheduling §6.37 that always runs the highest-priority ready thread, B would never stop being ready, A would never run again, and the result would be the deadlock of the previous case.

Stated precisely

Let LL be a spinlock built on an atomic exchange.

  1. Mutual exclusion, a safety property §1.11 (one that says something bad never happens): at most one thread holds LL at any moment. All exchanges on the lock word take place one after another, and each returns the value left by the one before. The lock word holds 0 only from a release (or the start) until the next exchange, so for each release at most one exchange returns 0. This guarantee needs no assumption about scheduling.

  2. Ordering: if acquisition uses acquire order and release uses release order, every write made in one critical section is visible to the next holder once it has acquired LL.

  3. Progress, a liveness property §1.12 (one that says something good eventually happens): a waiter acquires LL only after the holder executes its release. The holder reaches its release only under two conditions. (P1) Every critical section of LL finishes in bounded time and never sleeps or waits for another event. (P2) While a thread on core cc holds LL or waits for it, no other code that may try to acquire LL runs on core cc. Kernels meet P2 by disabling preemption, together with every interrupt whose handler takes LL, on core cc from before the first attempt to acquire until after the release.

Under P1 and P2 every waiter runs on a different core from the holder, so the holder keeps running and releases LL. Let HH be the longest time any thread holds LL, and let PP be the number of cores. P2 lets each core hold or wait for LL only once at a time, so with a ticket lock at most P−1P - 1 tickets, the holder’s included, are ahead of a new waiter. That waiter therefore waits at most (P−1)×H(P - 1) \times H, plus the time to hand the lock from core to core. With a test-and-set lock the system as a whole still progresses, but no bound exists for one particular waiter.

Limits and common mistakes

Spinning burns processor time and energy for the whole wait. Use a spinlock only when the expected wait is shorter than the cost of sleeping and waking; for long or unpredictable critical sections use a mutex.

Holding a kernel spinlock delays everything else on that core. Preemption, and often interrupts, stay disabled for the whole critical section, so every microsecond of it adds to the worst-case response time §9.32 of interrupts and of higher-priority threads.

Never sleep while holding a spinlock: no blocking call, no wait for input or output, no memory allocation that may wait. A holder that sleeps breaks P1, and every waiter on another core spins until the holder wakes.

A spinlock is not recursive. A thread that tries to acquire a spinlock it already holds spins forever.

Two spinlocks taken in opposite orders on two cores deadlock exactly as two mutexes do. Lock ordering §9.15, one fixed order in which every thread acquires locks, prevents it.

In an ordinary program the operating system can suspend a thread at any moment, and the program cannot prevent it. A spinlock written there loses the protection of P2: if the holder is suspended, every waiter spins through its time slice. Ordinary programs therefore use a mutex, or a lock that spins briefly and then sleeps.

In a test-and-set or ticket lock all waiters spin on one word, so every release disturbs every waiting core. Queue locks such as the MCS lock, named after its inventors, Mellor-Crummey and Scott [519], give each waiter its own flag.

A spinlock is a blocking algorithm §14.1, not a lock-free §9.13 one: if the holder stops, every waiter stops with it.

Questions answered

Can the holder be preempted by a waiter on the same core?

Yes, a waiter on the same core can preempt the holder unless the locking rules make that impossible, and when it happens the result is a deadlock or a long waste of processor time. A spinlock is a lock whose waiters spin, testing it in a loop, instead of sleeping. One processor core runs one thing at a time, so while a waiter that has suspended the holder spins on that core, the holder cannot run and cannot release the lock. If the waiter is an interrupt handler, the routine the processor runs when a device signals an event, the handler never returns and the core is stuck forever. A waiting thread of higher priority, under a scheduler that always runs the highest-priority ready thread, has the same result. A waiting thread of equal priority, under a scheduler that shares the core in time slices, wastes its entire slice before the holder can continue.

A correct design makes this preemption impossible: while a thread holds or waits for a spinlock, no code that may take the same lock may run on that core. Kernels enforce the rule by disabling preemption for that whole time and by also disabling, on that core, every interrupt whose handler takes the lock. In the Linux kernel these are spin_lock and spin_lock_irqsave; in the Zephyr real-time operating system, k_spin_lock masks interrupts on the local core. Turning a sleeping lock into a busy-waiting loop does not by itself make code safe to share with an interrupt handler.

Related entries: Deadlock (§9.14), Critical section (§9.4), Atomic operation (§9.8), Mutex (§9.5), Interrupt service routine (ISR) (§6.12), Cooperative and preemptive scheduling (§6.37), Lock ordering (§9.15). Further reading: [78, 519].