user1363410
user1363410

Reputation: 135

What would happen if pthread_cond_wait was not atomic?

Scenario 1: release mutex then wait Scenario 2: wait and then release mutex

Trying to understand conceptually what it does.

Upvotes: 1

Views: 228

Answers (1)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

If the mutex were released before the calling thread is considered "blocked" on the condition variable, then another thread could lock the mutex, change the state that the predicate is based on, and call pthread_cond_signal without the waiting thread ever waking up (since it's not yet blocked). That's the problem.

Scenario 2, waiting then releasing the mutex, is internally how any real-world implementation has to work, since there's no such thing as an atomic implementation of the necessary behavior. But from the application's perspective, there's no way to observe the thread being part of the blocked set without the mutex also being released, so in the sense of the "abstract machine", it's atomic.

Edit: To go into more detail, the real-world implementation of a condition variable wait generally looks like:

  1. Modify some internal state of the condition variable object such that the caller is considered to be part of the blocked set for it.
  2. Unlock the mutex.
  3. Perform a blocking wait operation, with the special property that it will return immediately if the state of the condition variable object from step 1 has changed due to a signal from any other thread.

Thus, the act of "blocking" is split between two steps, one of which happens before the mutex is unlocked (gaining membership in the blocked set) and the other of which happens after the mutex is unlocked (possibly sleeping and yielding control to other threads). It's this split that's able to make the "condition wait" operation "atomic" in the abstract machine.

Upvotes: 4

Related Questions