Course contentsShow
← Computer Science
Lesson 1306 of 2,87230. Process SynchronizationFree lesson

The Wait-Signal Pattern

Master the standard pattern: checking a condition, waiting if false, and being signaled when it becomes true.

The Wait-Signal Pattern

What You'll Learn

You'll learn the fundamental synchronization idiom that combines condition checking, waiting, and signaling to coordinate threads safely.

The Core Pattern

The wait-signal pattern is the standard recipe for using condition variables correctly. It ensures threads sleep when a condition isn't met and wake up when another thread makes it true.

Here's the essential structure:

Thread That Waits (Consumer of a Condition)

  1. Lock the mutex protecting shared state
  2. Check the condition in a while loop (not if!)
  3. If false, call wait() — this atomically releases the mutex and sleeps
  4. When awakened, recheck the condition (the while loop does this)
  5. Proceed when condition is true, still holding the lock
  6. Unlock the mutex when done

Thread That Signals (Producer of a Condition)

  1. Lock the mutex
  2. Change the shared state to make the condition true
  3. Call signal() or broadcast() to wake waiting threads
  4. Unlock the mutex

Why the While Loop?

You must use while instead of if because:

  • Spurious wakeups: Wait can return even when not signaled
  • Multiple consumers: Another thread might grab the resource first after you wake
  • Safety: Always verify the condition actually holds

Simple Analogy

Think of a doctor's waiting room. Patients (threads) check if the doctor is ready. If not, they wait (and stop checking actively). When the doctor finishes with someone, the nurse signals the next patient. That patient rechecks to confirm it's truly their turn before entering.

Key Takeaway: The wait-signal pattern combines three elements — loop-while-condition-false, wait inside that loop, and signal after making the condition true — to create safe, efficient thread coordination.