chapter 30 - condition variables Flashcards
What is a condition variable and what does it let a thread do?
A condition variable lets a thread sleep until a condition becomes true, and be woken up by another thread when the condition changes
Why must a mutex be used with pthread_cond_wait()?
To avoid race conditions where a signal might be missed if one thread signals before another actually begins waiting
Should you use if or while when waiting on a condition variable?
Use while, because the condition might have changed before the thread resumes after being signaled
What issue can occur if both producers and consumers use the same condition variable?
A consumer may accidentally wake another consumer, leading to deadlock if the buffer is empty and all threads go to sleep
How can you avoid deadlock with a single-item buffer?
Use two condition variables:
- empty for producers to wait on,
- fill for consumers to wait on,
and only signal the other type of thread
how is a condition variable used in pthreads?
It’s used in coordination with a mutex to ensure atomicity.
Why must condition variables be used with a mutex?
Without a mutex, a race condition can occur:
- eks:
Parent checks done == 0 and is about to call wait()
Child sets done = 1 and calls signal() before parent calls wait()
Parent then calls wait() and sleeps forever since no one signals again
Using a mutex ensures the check and wait are atomic, avoiding lost signals
What are the two cases that can happen when a parent waits for a child using condition variables?
Case 1:
Parent calls wait() and sleeps because done == 0
Child sets done = 1 and signals
Parent wakes and checks done == 1, proceeds
Case 2:
Child runs immediately, sets done = 1 before parent calls wait()
Parent sees done == 1 and skips waiting