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.
Practice this topic Back to topic

More Multicore & Synchronization questions

  1. Why does a spinlock usually wait with ordinary reads and use an atomic instruction only when the lock looks free (test-and-test-and-set), instead of retrying the atomic write directly?
  2. Which correctly compares a mutex (a lock that sleeps while waiting) with a spinlock?
  3. Which is an example of deadlock?
  4. In a program using several locks, what is the most common way to prevent deadlock?
  5. What does a memory consistency model define?