And a representative sequence for using condition variables is shown below.
To better understand condition variable, let us take a look at the answer to a Google interview question: how to measure the speed of context switch. The answer was given in:
Ah, UNIX stuff. Essentially you would create a function to alternate between persistant thread states, set lock and start/wakeup/sleep conditions plus a counter.
Next we create persistant threads t1 and t2 which are unlocked (awoken), and we roughly sleep one second to let them do their firing. (rough approximate of one second, granularity is different among platforms/clocks)
Here follows my explanation on how above code works:
At first, only one persistent thread (say t1) can lock LOCK, so t2 waits. t1 then fulfills the condition (COUNTER++) but waits. Since the main thread sleeps once it lets persistent threads go, so only the other persistent thread (t2) can be waken up (one switching). t2 signals CONDITION, but t1 cannot wait right now because t2 holds LOCK, and t1’s wait invocation have to wait until t2 unlocks LOCK. Therefore, t2 goes on increase COUNTER and waits. Since the wait invocation unlocks LOCK, so t1 now wakes up and signals CONDITION. Similarly, t2 cannot wake up right now but has to wait until t1 increase COUNTER and actively waits again.