Overview:
- In Python, the notify() method of the Condition class is used to notify other threads that are blocking for a predicate to become True.
- Before calling notify() the calling thread has to acquire the lock associated with the condition variable.
- The caller must release the underlying lock by calling release() after calling the notify() method on a Condition object.
- The notify() method by default wakes up one thread that is in blocked state using the same condition variable. By specifying a value greater than one notify() can be made wake up a specific number of waiting threads.
Example:
Though two consumer threads are notfied upon filling of the deque the consumers proceed one after another as the same lock is used by both the threads.
# Example Python program that uses the notify() method # A deque. It is filled by the producer # Target function for the producer thread # Target function for the consumer thread while(True): cv.release() # Create the lock object # Create the condition object # Create the producer thread start = 0 # Create the consumer threads start = start + end # Start all the threads # Wait for child threads to complete |
Output:
Producer has notified the consumers time:1757924039.893707 thread_id:6109425664 job_id:Job:10 time:1757924039.893742 thread_id:6109425664 job_id:Job:9 time:1757924039.893748 thread_id:6109425664 job_id:Job:8 time:1757924039.8937511 thread_id:6109425664 job_id:Job:7 time:1757924039.893754 thread_id:6109425664 job_id:Job:6 time:1757924039.8937652 thread_id:6126252032 job_id:Job:5 time:1757924039.89378 thread_id:6126252032 job_id:Job:4 time:1757924039.893782 thread_id:6126252032 job_id:Job:3 time:1757924039.893785 thread_id:6126252032 job_id:Job:2 time:1757924039.893787 thread_id:6126252032 job_id:Job:1 |