liveBook · Manning

Cnd_wait

As explained in Modern C, Third Edition

cnd_wait is a C threads-library function that atomically releases a mutex while waiting on a condition variable and reacquires it before returning.

Wait until the protected condition changes

mtx_lock(&L->mtx); while (!L->finished && (L->accounted == L->iteration)) cnd_wait(&L->acco, &L->mtx); /* safely access protected state here */ mtx_unlock(&L->mtx); section 20.5

cnd_wait blocks the calling thread on a condition variable. The calling thread must already hold the supplied mutex. During the wait, cnd_wait temporarily releases that mutex so another thread can update the protected state and signal the condition variable; immediately before returning, it reacquires the mutex. section 20.5

Use cnd_wait with these synchronization rules:

  • Protect the condition expression with the same mutex passed to cnd_wait. section 20.5
  • Place the call inside a while loop and retest every part of the condition after it returns; an untimed wait may return early. section 20.5
  • Use cnd_signal to wake one waiter or cnd_broadcast to wake all waiters associated with the condition variable. section 20.5
  • Associate a condition variable with one mutex at a time, although several condition variables may share that mutex. section 20.5

How Modern C, Third Edition covers it

How deep it goes
Explains mutex release, reacquisition, signaling, early returns, and condition-loop discipline, but not implementation internals.
Examples
Uses account, update, and draw threads waiting in mutex-protected loops for iteration, completion, or display-state changes.
What it assumes
Assumes mutex locking and shared-state conditions, while teaching the waiter's atomic release-and-reacquire relationship.
What you can do after
Apply cnd_wait through a mutex-protected while loop that safely waits for and rechecks shared state.
How it connects
Connects condition variables with mutexes, critical sections, cnd_signal, cnd_broadcast, and memory synchronization.

Also explained in

Compare how 2 books explain cnd_wait →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.