30. Condition variables Flashcards
What is condition variable?
It’s an explicit queue that threads can put themselves on when some state of execution (some condition) is not as desired. Some other thread, when it changes said state, can then wake those waiting thread(-s) by signaling.
Definition of condition variable
pthread cond_t c = null;
Provide interfaces for wait() and signal() calls for threads
pthread_cond_wait(pthread_cond_t *c, pthread_mutex_t *m);
pthread_cond_signal(pthread_cond_t *c);
What’s responsibility of wait() call?
The wait() call assumes that the passed lock is already held when it’s called. It’s responsibility is to release the lock and put the calling thread to sleep (atomically). When the thread wakes up after signal, it must re-acquire the lock before returning to the caller.
Why are locks around changing the state variable, signaling, waiting are important?
To avoid race condition since the state of condition variable also changes. And to avoid forever sleeping threads
What’s responsibility of signal() call?
To wake up a thread from a queue (condition variable) and let it recheck its condition and decide whether it can execute further or go back to sleep
What issue can arise when consumer/producer threads use the same single condition variable? Considering we can’t do a broadcast call
They might all go to sleep because wrong thread (i.e consumer-consumer or producer-producer) is woken up
Why should we use while and not if while checking the condition variable?
Because another thread might sneak in after the original thread was woken up. In this case, the sneaky thread will consume a value from some buffer and the original thread will continue its execution without recheck failing because buffer is now empty
How is an issue of wakening up a wrong thread in memory allocation library is solved?
With broadcast signaling pthread_cond_broadcast().