← Lessons

quiz vs the machine

Silver1090

Concurrency

The Spinlock

A lock that busy waits in a tight loop instead of sleeping.

4 min read · intro · beat Silver to climb

The Spinlock

A spinlock is the simplest mutual exclusion primitive. To acquire it a thread repeatedly tries to swap a flag from free to held using an atomic compare and swap. If the swap succeeds the thread owns the lock. If it fails the thread loops and tries again, spinning in place rather than going to sleep.

This busy waiting is the defining trait. A sleeping lock asks the operating system to park the thread and wake it later, which costs a context switch. A spinlock skips that cost, so it shines when the critical section is very short and the wait will be measured in nanoseconds.

  • No context switch which is why it is fast for tiny critical sections.
  • Wastes a core while spinning, since the waiting thread burns cycles doing nothing useful.
  • Dangerous when held long A holder that sleeps or is preempted leaves spinners burning power for nothing.

Kernels use spinlocks where they cannot sleep, for example inside interrupt handlers. In user space they are usually a poor default because a preempted holder can stall many spinners.

Key idea

A spinlock busy waits on an atomic swap, trading wasted cycles for the speed of avoiding a context switch on very short critical sections.

Check yourself

Answer to earn rating on the learn ladder.

1. What does a thread do when it fails to acquire a spinlock?

2. When is a spinlock a good choice?