Experiments and implementations · Intermediate

Testing why condition variables need predicate loops

Send a notification without changing the shared predicate and verify why returning from a condition wait does not itself authorize progress.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Create a controlled false-predicate notification
  2. Observe the second predicate check
  3. A notification is not a reservation
  4. Understand why waiting releases the lock
  5. Include timeout and shutdown in the state model
  6. Ask Logeia about this articleCheck your understanding

Create a controlled false-predicate notification

The experiment deliberately notifies a condition while its shared ready predicate remains false. It does not force the operating system to produce a spontaneous return without notification, which is another meaning of spurious wakeup. Instead, it reproduces an equally important case: even a real notification does not establish that the predicate currently permits progress. Use only Python threading.Condition and Event, without external services or administrator privileges. Read and write the shared predicate while holding the same condition lock. Events coordinate the demonstration’s stages; they do not replace checking the actual shared condition or confer ownership of a resource promised by a notification.

Observe the second predicate check

The waiter checks while-not-ready, signals that its first check has begun, and waits on the condition. The main thread then notifies without changing ready. A second event confirms that the waiter has returned and checked the false predicate again. Assert that useful work is still incomplete at that stage. Finally set ready to true under the lock, notify again and wait for completion. Explicit stage coordination avoids guessing progress from a chosen sleep duration. Every event wait and condition wait has a bound. Capture worker exceptions and inspect them in the main thread so a failed worker cannot silently turn a demonstration of correct waiting into a misleading success message.

python
import threading
cv = threading.Condition()
first, second, done = (threading.Event() for _ in range(3))
ready = False
errors = []
def waiter():
    try:
        with cv:
            checks = 0
            while not ready:
                checks += 1
                (first if checks == 1 else second).set()
                if not cv.wait(timeout=3):
                    raise TimeoutError('predicate did not become ready')
            done.set()
    except BaseException as error:
        errors.append(repr(error))
t = threading.Thread(target=waiter, daemon=True)
t.start()
assert first.wait(3)
with cv:
    cv.notify()
assert second.wait(3) and not done.is_set()
with cv:
    ready = True
    cv.notify()
assert done.wait(3)
t.join(3)
assert not t.is_alive() and not errors
print('false notification rechecked; true predicate completed')

A notification is not a reservation

Condition wait returns after reacquiring the associated lock. Another participant may change shared state before that reacquisition, so a notification does not reserve a queue slot or certify the current predicate. This example keeps only one waiter and makes the same distinction visible by notifying a false condition directly. Replacing the loop with a single if can allow execution after an unsuitable return. Counting notifications as if each represented one available item is also incorrect. The authority to proceed comes from the current protected state, not a history of wakeups. This separation matters even when an operating system never happens to generate a spontaneous wakeup during a particular test run.

Understand why waiting releases the lock

If a waiter retained the condition lock while continuously testing ready, the producer could not acquire that lock to make ready true. Condition.wait releases the lock while blocked and reacquires it before returning. Checking and waiting according to the condition-variable protocol avoids introducing an unprotected gap between inspecting state and becoming a waiter. Replacing that protocol with “unlock, then sleep using some other notification mechanism” requires separate reasoning about missed notifications in the gap. Keep mutual exclusion, waiting for a predicate and coordinating demonstration stages as distinct responsibilities. The extra Event objects here make the experiment observable, while the condition lock remains responsible for the application state.

Include timeout and shutdown in the state model

A production predicate may include shutdown or cancellation as well as readiness. Wake blocked participants during shutdown and decide explicitly whether accepted work is drained or canceled. Do not treat a timeout return as a successful condition without rechecking state. This short verification program treats a timeout as an experiment failure rather than a business-level completion. It does not establish fairness, absence of starvation or higher throughput. Record the demonstrated stages: the second check observes no completion, then a true predicate permits completion. A notification, a successful predicate check and a completed operation are three separate events, and the report should preserve that distinction rather than combining them into one vague wakeup success.

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Build your CS foundations · STEP 18

Understand the systems behind the web · STEP 15

Choose a learning path