Overview:
- The wait() method blocks when the predicate it is waiting for is currently False. To wait on a condition variable the underlying lock must be acquired by the calling thread.
- When the predicate becomes True the waiting thread is notified of by another thread - the wait() releases the lock and proceeds with the work. Typically, doing some work makes the predicate to become False again.
- Waiting when a predicate is False and waking up from the waiting upon the predicate becoming True continues in a while loop. If a terminal condition is handled then the while loop breaks when the terminal condition becomes True.
- When no lock object is specified for the Condition variable, Python uses an RLock object as the underlying lock for the Condition.
- The example Python program that uses a condition variable in the introduction notifies the waiting thread(s) whenever there is an element available in the list for consumption. In the example below, the producer thread notifies only upon the deque becoming full.
Example:
# Example Python program that wakes up a consumer thread import collections as coll # The double ended queue whose maximum length is 5 # Target function for the producer thread # Target function for the consumer thread cvar.release() # Create the underlying lock # Create the condition variable # Create the producer and consumer threads # Starting the consumer thread first... # Wait for the producer and consumer threads to finish |
Output:
Producer:Notifying |