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
- Is a kind of: Mutex
- Is built on: Atomic variable, Busy waiting
- See also: Busy waiting
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¶
- In the books: Learn Concurrent Programming with Go, James Cutajar — ch. 12, 'Atomics, spin locks, and futexes'
- In the books: Rust Atomics and Locks, Mara Bos — ch. 4, 'Building Our Own Spin Lock'
- In the books: The Art of Multiprocessor Programming, Maurice Herlihy, Nir Shavit — ch. 7, 'Spin Locks and Contention'
- In the books: Advanced Programming in the UNIX Environment, W. Richard Stevens, Stephen A. Rago — ch. 11, 'Threads' → 'Spin Locks'
- Notes: Spinlock in general ↗
- Reference: Wikipedia: Spinlock ↗