Overview:
- A Condition variable signals a predicate becoming true which wakes up the threads waiting for such states. For example, availability of an item in a list is a predicate which can be signaled to a thread waiting for that state.
- A thread can be made to wait for a predicate to become True through the wait() method of the Condition object.
- Signaling of a condition, a predicate becoming true is communicated through the notify() method of the Condition object.
- Prior to waiting on a condition object, the associated lock must be acquired by the calling thread.
- After notify() the lock must be released by the calling thread.
Example:
# Example Python program that uses a condition variable items = [] # Function defintion for the producer thread while(True): # Function defintion for the consumer thread if(shouldExit == True): cv.release() # Create a lock # Create a condition variable # Create a producer thread # Create a consumer thread # Start the consumer and producer threads # Wait for the child threads to complete print("Producer and consumer threads exited") |
Output:
Pre-wait Produced:Item 1 Consumed:Item 1 Pre-wait Produced:Item 2 Consumed:Item 2 Pre-wait Produced:Item 3 Consumed:Item 3 Pre-wait Produced:Item 4 Consumed:Item 4 Pre-wait Produced:Item 5 Consumed:Item 5 Pre-wait Produced:Item 6 Consumed:Item 6 Pre-wait Produced:Item 7 Consumed:Item 7 Pre-wait Produced:Item 8 Consumed:Item 8 Pre-wait Produced:Item 9 Consumed:Item 9 Pre-wait Produced:Item 10 Consumed:Item 10 Consumer: This wakeup is for pop + exit Producer and consumer threads exited Main thread exiting |