Interview Q&A / Operating Systems

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What is a spinlock, and when is it better than a lock that puts the thread to sleep?

SHORT ANSWER

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

text
while (test_and_set(lock) == 1)
    ;                        // spin until we see 0
critical_section()
lock = 0

If 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.

#spinlock#synchronization

Related questions

Practise more Operating Systems questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Operating Systems quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.