Skip to content

Spinlock

Category: Synchronization · Status: stub

One line: A lock that waits by looping and retrying instead of sleeping, which pays off only when it is held for very short times.

Also called: spin lock, spin-wait.

How it connects

flowchart LR
  n_atomic_variable["Atomic variable"]
  n_busy_waiting["Busy waiting"]
  n_mutex["Mutex"]
  n_spinlock["Spinlock"]
  n_spinlock -->|is a| n_mutex
  n_spinlock -->|uses| n_atomic_variable
  n_spinlock -->|uses| n_busy_waiting
  classDef center stroke-width:3px
  class n_spinlock center
  classDef outside stroke-dasharray: 4 3
  class n_atomic_variable,n_busy_waiting,n_mutex outside

In each language

Rust std::hint::spin_loop tells the processor it is running in a busy-wait spin loop
C++ std::atomic_flag is guaranteed lock-free; its page builds a spinlock from it and warns that spinlock mutexes are extremely dubious in practice
Java Thread.onSpinWait tells the runtime that a loop is busy-waiting
C# SpinLock: a thread that wants the lock waits in a loop, checking again until it is free
The operating system POSIX pthread_spin_lock; in the Linux kernel the spinlock ↗ is the most basic locking primitive

Where to read more