What is a spinlock, and when is it better than a lock that puts the thread to sleep?
A spinlock makes a waiting thread loop on the CPU until the lock is free. It is better when the lock is held for a very short time, because sleeping and waking cost more than a brief spin.
Explain it simply
Waiting for a friend who is two minutes away, you stand at the gate and keep looking. Waiting for someone an hour away, you go home and ask them to call you. Standing and watching is a spinlock; going home is a sleeping lock (mutex).
A spinlock repeatedly tests the lock variable in a tight loop (busy waiting). It never gives up the CPU, so there is no context switch.
- Spin: wasteful if the wait is long, since the CPU does no useful work.
- Sleep: puts the thread in the waiting queue; costs two context switches (sleep and wake).
Example
while (test_and_set(lock) == 1)
; // spin until we see 0
critical_section()
lock = 0If the critical section takes about 50 nanoseconds and a context switch takes a few microseconds, spinning is cheaper by a wide margin. If the critical section waits for disk I/O (milliseconds), spinning would waste millions of cycles.
Spinlocks only make sense on multiprocessor machines. On a single core, the thread holding the lock cannot run while another thread spins, so spinning just wastes the time slice. Operating system kernels use spinlocks for short critical sections inside interrupt handlers, where sleeping is not allowed.
What to say in the interview
"A spinlock busy-waits instead of sleeping. It wins when the critical section is shorter than the cost of two context switches and there is more than one core. For long waits or single-core systems a sleeping mutex is better."
Common mistakes
- Using spinlocks around code that can block on I/O.