Multicore & Synchronization

In which situation is a spinlock least suitable?

  1. AWhen the lock is held for a long time, so waiting threads waste CPU time spinning
  2. BWhen the lock is held only for tens of nanoseconds
  3. CInside an OS kernel, in code that is not allowed to sleep
Show answer and explanation

Answer: A. When the lock is held for a long time, so waiting threads waste CPU time spinning

A thread waiting on a spinlock keeps using the CPU until the lock is free. If the lock is held for long, all that CPU time is wasted and other threads are held back. On a single core it is worse: the lock cannot be released unless the holder runs, so the waiter spins until its time slice ends. Long waits call for a mutex that sleeps, and some locks spin briefly before sleeping.

  • A. Correct. A lock that sleeps is more efficient then.
  • B. Short holds are exactly where spinlocks shine.
  • C. Spinlocks are used where sleeping is not allowed.