Condition Variables

Allow threads to wait for arbitrary conditions to become true

Each CV corresponds to a particular condition that is of interest to an application

Example

  • cond_t nonemptycount > 0 (there are items in the buffer)
  • cond_t nonfullcount < BUFFER_SIZE (there is free space in the buffer)

When condition is not true, thread can cond_wait until condition becomes true

Always recheck conditions on wake up

while (count == 0)
	cond_wait(&nonempty, &mutex)

Do not use if

  • Condition may change
Why must cond_wait both release mutex and sleep?

Will Deadlock if sleep with locked mutex

Why not separate mutexes and CV?

Can end up stuck waiting when bad interleaving

  • Another thread acquires the same lock and signals

PThread CV API