Multicore & Synchronization

When waiting on a condition variable until a queue becomes non-empty, why is the condition rechecked in a while loop rather than an if after waking?

  1. AA while loop runs faster than an if statement
  2. BCondition variables cannot be used with if statements
  3. CEven after waking, another thread may have taken the item first or the wake-up may be spurious, so the condition may not hold
Show answer and explanation

Answer: C. Even after waking, another thread may have taken the item first or the wake-up may be spurious, so the condition may not hold

Waiting on a condition variable releases the lock and sleeps; when signaled, the thread reacquires the lock and returns. But before it does, another thread may grab the lock and take the queue element. Implementations are also allowed to wake a thread with no signal at all (a spurious wake-up). So the code checks the condition after waking and waits again if it does not hold, using a while loop.

  • A. It is not about speed.
  • B. There is no such rule.
  • C. Correct. The condition must be rechecked after waking.
Practice this topic Back to topic

More Multicore & Synchronization questions

  1. Two cores each hold a copy of variable x in their own caches. After core 0 writes x, what problem could occur when core 1 reads x if there were no cache coherence mechanism?
  2. Which correctly lists the four states of the MESI cache coherence protocol?
  3. In the MESI protocol, what does it mean when a cache line is in the Modified (M) state?
  4. In the MESI protocol, what happens when a core writes to a line it holds in the Exclusive (E) state?
  5. In an invalidation-based coherence protocol, what happens when a core writes to a line in the Shared (S) state?