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 Dijkstra’s use of “private semaphores”“Cooperating sequential processes” by Edsger W. Dijkstra. 1968. Available online here: http://www.cs.utexas.edu/users/EWD/ewd01xx/EWD123.PDF. Another classic from Dijkstra; reading his early works on concurrency will teach you much of what you need to know.; a similar idea was later named a “condition variable” by Hoare in his work on monitors“Monitors: An Operating System Structuring Concept” by C.A.R. Hoare. Communications of the ACM, 17:10, pages 549–557, October 1974. Hoare did a fair amount of theoretical work in concurrency. However, he is still probably most known for his work on Quicksort, the coolest sorting algorithm in the world, at least according to these authors..

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.