Learning about condition variables, read-write locks, and ranges in C++
Let’s now start our discussion of synchronization primitives, a fundamental one of which is the condition variable. Its purpose is to allow multiple threads to remain blocked until an event occurs (i.e., a condition is satisfied). The implementation of condition variables requires an additional Boolean variable to indicate whether the condition is met or not, a mutex to serialize the access to the Boolean variable, and the condition variable itself.
POSIX provides an interface for multiple use cases. Do you remember the producer-consumer example in Chapter 7, Using Shared Memory? So, pthread_cond_timedwait()
is used to block a thread for a given period of time. Or simply wait for a condition through pthread_cond_wait ()
and signal with pthread_cond_signal()
to one thread, or pthread_cond_broadcast()
to all threads. Typically, the condition is checked periodically in the scope of a mutex lock:
... pthread_cond_t...