Condition Variables/Variables Condición

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

  1. locks count_mutex,
  2. increments count,
  3. reads count in a print statement, and tests for the threshold value.
  4. If count has reached its threshold value, inc_count emits a signal to notify the thread that's waiting for this particular event.
  5. Before exiting, inc_count releases the mutex.

  6. We'll create a third thread to run the 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