A spinlock is a mutual exclusion lock in which a thread that cannot acquire the lock repeatedly tests it in a tight loop, or spins, until the current owner releases it. In concurrency and systems programming, it is the simplest lock that can be built from a single atomic read-modify-write instruction, and it trades wasted processor cycles for the lowest possible handoff latency.
Spinlocks are a core tool inside operating system kernels, hypervisors, memory allocators and real-time code, where critical sections last only a few hundred nanoseconds and putting a thread to sleep would cost far more than waiting. Used outside those conditions, they become one of the most common sources of wasted CPU time and priority problems in concurrent software.
How a spinlock acquires and releases ownership
A spinlock works by atomically changing a shared flag from unlocked to locked and retrying until that change succeeds. The flag is usually a single machine word. Acquisition uses an atomic instruction such as test-and-set, atomic exchange or compare-and-swap, so that exactly one thread observes the transition from 0 to 1 even when many cores attempt it at the same moment.
Release is a plain store of 0 with release memory ordering, and acquisition must carry acquire ordering. These orderings act as a memory barrier that prevents the processor and the compiler from moving reads or writes of protected data outside the critical section. A spinlock without correct ordering may appear to work on x86, which has a strong memory model, and then fail on ARM or POWER, which reorder more aggressively.
The following table lists the building blocks that appear in practical spinlock implementations and the role each one plays.
| Component | Typical implementation | Purpose |
|---|---|---|
| Lock word | One aligned integer or byte | Holds the locked or unlocked state |
| Atomic acquire | Exchange, test-and-set or CAS | Guarantees a single winner |
| Spin loop | Plain load until the word looks free | Waits without bus-locking traffic |
| Pause hint | PAUSE on x86, YIELD or WFE on ARM | Saves power and frees pipeline resources |
| Release store | Store 0 with release ordering | Publishes writes and frees the lock |
A well-written loop uses the test-and-test-and-set pattern: it spins on an ordinary read, which stays in the local cache, and attempts the expensive atomic operation only when the lock appears free. Naive loops that issue an atomic exchange on every iteration cause cache-line ping-pong, in which the line holding the lock bounces between cores and slows down even the owner.
Spinlock variants and their fairness properties
Spinlock designs differ mainly in fairness and scalability under contention. A basic test-and-set lock lets whichever core wins the cache race take ownership, so a thread can lose many times in a row. Queue-based designs hand the lock over in arrival order and keep each waiter spinning on its own cache line.
The table below compares the variants that appear most often in kernels and runtime libraries.
| Variant | Fairness | Behavior under heavy contention |
|---|---|---|
| Test-and-set lock | None | Severe cache traffic, possible starvation |
| Test-and-test-and-set lock | None | Less traffic, still unfair |
| Ticket lock | First in, first out | All waiters poll one shared counter |
| MCS lock | First in, first out | Each waiter spins on a private node |
| Queued spinlock | First in, first out | Compact MCS variant used in the Linux kernel |
| Reader-writer spinlock | Varies by design | Allows many readers, writers may starve |
Ticket locks work like a deli counter: each arriving thread takes the next number and spins until the serving counter matches it. MCS locks go further by building a linked queue of waiters, so the release operation touches only the next thread’s cache line. This keeps cross-core traffic roughly constant per handoff instead of growing with the number of waiting cores.
Spinlock compared with mutex and other primitives
The essential difference between a spinlock and a mutex is what a waiting thread does: a spinlock keeps the thread running, while a mutex asks the scheduler to block the thread and wake it later. Blocking costs a system call and two context switches, often several microseconds, but it frees the core for useful work.
| Primitive | Waiting strategy | Best fit |
|---|---|---|
| Spinlock | Busy-waits on the CPU | Critical sections under about one microsecond |
| Mutex | Sleeps in the scheduler | Longer or unpredictable critical sections |
| Adaptive mutex | Spins briefly, then sleeps | General user-space code |
| Semaphore | Sleeps, counts permits | Limiting access to a pool of resources |
| Lock-free structure | Retries an atomic update | Hot paths that must avoid blocking |
Most modern user-space mutexes, including futex-based implementations on Linux, are in fact hybrid locks that spin for a short time before sleeping. For that reason, an application programmer rarely gains anything by writing a raw spinlock, and the decision matters most to authors of kernels, drivers and lock libraries.
When a spinlock is the right choice
A spinlock is appropriate when the expected wait is shorter than the cost of blocking and the lock holder is guaranteed to be running on another core. Both conditions matter. If the owner can be descheduled while it holds the lock, waiters may spin for an entire scheduler time slice of several milliseconds.
| Situation | Recommended choice | Reason |
|---|---|---|
| Interrupt handler on a multiprocessor | Spinlock with interrupts disabled | Sleeping is not permitted there |
| Update of a few fields, many cores | Spinlock or atomic operation | Hold time is tiny and predictable |
| Disk or network I/O inside the section | Mutex | Hold time is long and unpredictable |
| Single-core system | Disable preemption or use a mutex | Spinning can never succeed early |
| Oversubscribed threads in user space | Adaptive mutex | Owner may be descheduled |
Inside kernels, acquiring a spinlock normally also disables preemption, and the interrupt-safe variants disable local interrupts as well. This guarantees that the holder keeps running and that an interrupt handler on the same core cannot attempt to take a lock the interrupted code already owns, which would be an immediate self-deadlock.
Common spinlock pitfalls and failure modes
Most spinlock bugs come from holding the lock too long or from scheduling assumptions that do not hold. The consequences range from lost throughput to complete system hangs, and many of them appear only under production load.
- Sleeping while holding a spinlock, for example by allocating memory that may block, can stall every other core waiting for the lock.
- Priority inversion occurs when a low-priority owner is preempted and a high-priority waiter burns its time slice spinning.
- Lock-holder preemption in virtual machines lets a hypervisor deschedule the virtual CPU that owns the lock; paravirtualized spinlocks exist to mitigate it.
- False sharing places the lock word on the same cache line as frequently written data and slows both.
- Missing memory ordering allows protected writes to become visible after release, producing a subtle race condition.
- Recursive acquisition by the same thread deadlocks, because ordinary spinlocks are not reentrant.
A practical rule is that nothing that can block belongs inside a spinlock: no I/O, no page faults, no waiting on other locks of a different class, and no unbounded loops. Measuring hold times with lock statistics or tracing tools is the most reliable way to confirm that a spinlock is still the correct primitive as code evolves.
Put simply
A spinlock is like waiting outside a single restroom. You stand at the door and try the handle again and again. If the person inside will be out in seconds, this is the fastest way in. There is no need to walk away and be called back.
If the person inside will take twenty minutes, rattling the handle wastes time. Spinlocks are excellent for very short waits and wasteful for long ones. That is why programs often switch to locks that let the waiting side rest.
In practice
A network driver on a 32-core server keeps a ring buffer of packet descriptors that is shared by the interrupt handler and by several transmit threads. Each update touches only a head index and one descriptor, taking roughly 100 to 200 nanoseconds. The driver protects the ring with an interrupt-safe spinlock, because the interrupt handler is not allowed to sleep and a mutex would add microseconds to every packet.
During load testing, engineers notice that one code path also calls a logging function inside the locked region, and that function occasionally waits for a console buffer. Lock statistics show hold times spiking to several milliseconds and throughput dropping by about a third. After the logging call is moved outside the critical section, median hold time returns to under 200 nanoseconds and the server sustains its target packet rate, confirming that the spinlock is appropriate only while the protected work stays tiny.