A condition variable is a controlled way of communicating an event (or a condition) between two threads.
One thread can wait on the condition, and the other can signal it.
The Thread library extends threads with condition variables.
A condition variable is basically a container of threads that are waiting on a certain condition.
Condition variables provide a kind of notification system among threads.
Without condition variables, but only mutexes, threads would need to poll the variable to determine when it reached a certain state.
The example shows a simple use of a condition variable. We'll
make the global variable count a shared resource that two threads
increment and create the mutex count_mutex to
protect it.
We'll use the count_threshold_cv condition variable to represent an
event
the count variable's reaching a defined threshold value,
WATCH_COUNT.
The main routine creates two threads.
Each of these threads runs the inc_count routine.
The inc_count routine
count_mutex,
count,
count in a print statement, and tests
for the threshold value.
count has reached its threshold value,
inc_count emits a signal to notify the thread that's waiting for this particular event.
inc_count releases the mutex.
watch_count task.
The watch_count routine waits for inc_count to signal our
count_threshold_cv condition variable.
Casiano Rodriguez León 2015-01-07