Questions: Condition Variables: Usage Patterns and Pitfalls

5 questions to test your understanding

Score: 0 / 5
Question 1 Multiple Choice

A thread wakes from a condition variable wait() call and finds the condition it was waiting for is still false. In a correctly written program, what should happen next?

AThe thread should proceed anyway — if it was signaled, the condition must be true
BThe thread should release the lock and terminate, since the wakeup was erroneous
CThe thread should re-check the condition in its while loop and call wait() again
DThis cannot happen if the signaling thread holds the lock when it calls signal()
Question 2 Multiple Choice

A bounded buffer uses a single condition variable shared by both producers (waiting when full) and consumers (waiting when empty). A producer adds an item and calls signal(). What could go wrong?

ANothing — signal() correctly wakes one waiting thread, which will then check its condition
BAnother producer could be woken instead of a consumer, find the buffer still full, and go back to sleep without notifying any consumer
CThe signaled thread will always be a consumer because signal() uses FIFO ordering
Dsignal() is invalid unless called with the lock held, causing undefined behavior
Question 3 True / False

Using `if (!condition) wait(cv, lock)` instead of `while (!condition) wait(cv, lock)` is safe as long as the signaling thread typically holds the lock when it calls signal().

TTrue
FFalse
Question 4 True / False

Using broadcast() in place of signal() is always correct, even if it causes unnecessary wakeups.

TTrue
FFalse
Question 5 Short Answer

Explain what 'barging' is in the context of condition variables, and why it requires waits to be in a while loop rather than an if statement.

Think about your answer, then reveal below.