Spinlocks vs Mutexes: When Spinning Wins
A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

Two threads want the same lock. A mutex that cannot be taken puts the caller to sleep and asks the kernel to wake it when the lock is free. A spinlock keeps the caller on the CPU, re-checking the lock in a tight loop. The folk rule is that spinlocks are for very short critical sections and mutexes for everything else. The rule is mostly right, and its exceptions matter, because a spinlock used in the wrong place can hand the CPU to a thread that is waiting for a lock held by a thread that is not running. This post compares the costs, writes a correct spinlock in C11, shows the decision table, and covers the failure that makes user-space spinlocks dangerous. It uses gcc 13 on Linux x86-64 with glibc 2.39.
What each one does
A modern mutex, such as glibc's pthread_mutex_t of the default type, is implemented with a futex on Linux. The fast path is one atomic compare-and-swap in user space: if the lock is free, the thread takes it with no system call. If the lock is held, the thread calls futex(FUTEX_WAIT), the kernel parks it on a wait queue, and the unlocker calls futex(FUTEX_WAKE). The sleep costs two context switches and a system call or two, which is thousands of cycles, but the waiting thread consumes no CPU while it sleeps.
A spinlock never calls into the kernel. The waiter loops reading the lock word until it clears, then tries to take it. There is no wake-up latency beyond the cache line transfer, and the thread uses 100 percent of a core while it waits.
So the trade is wake-up latency against CPU burned. Spinning wins when the expected wait is shorter than the cost of sleeping and waking, and the thread holding the lock is running on another CPU right now, so it will release soon.
A correct spinlock
The simplest correct spinlock uses C11 atomics: an exchange with acquire ordering to take the lock, and a store with release ordering to drop it.
#pragma once
#include <stdatomic.h>
#include <stdbool.h>
typedef struct { atomic_bool locked; } spinlock_t;
static inline void spin_lock(spinlock_t *l)
{
for (;;) {
if (!atomic_exchange_explicit(&l->locked, true, memory_order_acquire))
return;
while (atomic_load_explicit(&l->locked, memory_order_relaxed))
__builtin_ia32_pause();
}
}
static inline void spin_unlock(spinlock_t *l)
{
atomic_store_explicit(&l->locked, false, memory_order_release);
}Three details deserve a sentence each. The inner while reads without writing, a test-and-test-and-set pattern: spinning with the atomic exchange itself would make every waiter write the line on every iteration and flood the interconnect with invalidations, while a read leaves the line Shared in each waiter's cache until the owner writes it. __builtin_ia32_pause emits the PAUSE instruction, which the Intel SDM describes as a hint that improves spin-wait loops by reducing power and avoiding a memory-order violation penalty when the loop exits, and it is specific to x86, so portable code wraps it in a macro and uses yield on AArch64. And the memory orders are the minimum: acquire on the successful lock so the critical section cannot move above it, release on unlock so it cannot move below.
Use it:
#include <pthread.h>
#include <stdio.h>
#include "spinlock.h"
static spinlock_t lock;
static long counter;
static void *work(void *arg)
{
(void)arg;
for (int i = 0; i < 1000000; i++) {
spin_lock(&lock);
counter++;
spin_unlock(&lock);
}
return NULL;
}
int main(void)
{
pthread_t a, b;
pthread_create(&a, NULL, work, NULL);
pthread_create(&b, NULL, work, NULL);
pthread_join(a, NULL);
pthread_join(b, NULL);
printf("counter = %ld\n", counter);
return 0;
}counter = 2000000The critical section is one increment, which is the case spinlocks are for. Compile with gcc -O2 -pthread use_spin.c.
The danger: preemption while holding the lock
Here is why the folk rule exists. A spinlock assumes the lock holder is running. In user space, the operating system can preempt any thread at any time, including one that holds your spinlock. Now the waiters spin, burning their whole time slices waiting for a thread that cannot run because they are occupying the cores. With more runnable threads than cores, a preempted lock holder can leave several cores spinning uselessly until the scheduler gets round to the holder. The kernel's own spinlocks avoid this by disabling preemption while they are held, and user space cannot.
The symptoms are latency spikes and throughput collapse under load, which do not appear in a benchmark with fewer threads than cores. Spinning with a bounded count, then falling back to sleeping, limits the damage: spin for a short time, a few hundred iterations, then call sched_yield() or block on a futex. glibc offers this as an adaptive mutex: PTHREAD_MUTEX_ADAPTIVE_NP, a GNU extension, spins briefly before sleeping.
#define _GNU_SOURCE
#include <pthread.h>
int make_adaptive_mutex(pthread_mutex_t *m)
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ADAPTIVE_NP);
int rc = pthread_mutex_init(m, &attr);
pthread_mutexattr_destroy(&attr);
return rc;
}The adaptive type is documented in pthread_mutexattr_settype(3), with the caveat that it is not portable. It gives you most of the spinlock's benefit on short critical sections and a sleep when the wait turns out long.
The decision table
| Situation | Choose | Reason |
|---|---|---|
| Critical section is a few instructions, threads at most equal to cores, threads pinned | Spinlock | No wake-up cost, holder is running |
| Critical section does I/O, allocation or can block | Mutex | The waiter would spin through the whole wait |
| More runnable threads than cores | Mutex | A preempted holder strands the spinners |
| Unknown or varying hold times | Adaptive mutex | Short spin, then sleep |
| Interrupt handler or kernel code with preemption off | Spinlock | Sleeping is not allowed |
| Real-time thread that must not sleep | Spinlock with care | Priority inversion needs a plan |
The table's first row is narrow, and most application code is better off with a plain mutex. A glibc mutex's uncontended lock and unlock cost about as much as the spinlock's, since both are one atomic operation, so the mutex loses only under contention, where the spinlock's advantage is also hard to keep. We think the default should be the mutex, with a spinlock reserved for code you have measured and pinned.
Measuring it yourself
Write the counter loop above twice, once with each lock, and run with thread counts from 1 up to twice the core count. Time each with perf stat or clock_gettime. What you should see is the spinlock competitive or better up to the core count, and degrading sharply once threads outnumber cores, while the mutex degrades gently. Record context switches with perf stat -e context-switches as the post on measuring context switch costs does. On a laptop with frequency scaling, repeat the runs, since the result is noisy.
A note on fairness
A simple spinlock is not fair. When the owner releases, whichever waiter happens to observe the cleared flag first wins, and a thread that is unlucky can keep losing. Ticket locks fix this by handing out numbers: a thread takes the next ticket with an atomic add and spins until the now-serving counter reaches its number, so waiters are served in arrival order. Fairness has a price, though. With a ticket lock, a preempted waiter holds up everyone behind it, since the lock waits for that specific thread, which makes the preemption problem worse. Mutexes make no strong fairness promise either, and the kernel's futex wake-up picks a waiter for you. If starvation matters to your workload, measure the maximum wait, not only the average.


