Definition and Routines
This lesson discusses the basics of a conditional variable, along with a shot at its implementation.
We'll cover the following
To wait for a condition to become true, a thread can make use of what is known as a condition variable. A condition variable is an explicit queue that threads can put themselves on when some state of execution, i.e., some condition, which is not as desired by waiting on the condition. Some other thread, when it changes said state, can then wake one or more of those waiting threads and thus allow them to continue by signaling on the condition. The idea goes back to
Syntax and usage
To declare such a condition variable, one simply writes something like this: pthread_cond_t c;
, which declares c
as a condition variable (note: proper initialization is also required). A condition variable has two operations associated with it: wait()
and signal()
. The wait()
call is executed when a thread wishes to put itself to sleep; the signal()
call is executed when a thread has changed something in the program and thus wants to wake a sleeping thread waiting on this condition. Specifically, the POSIX calls look like this:
Get hands-on with 1200+ tech skills courses.