import threading event = threading.Event() def wait_for_event(): print("Waiting for event") event.wait() # Wait for the event to be set print("Event has been set, proceed with execution") def set_event(): print("Setting the event") event.set() thread1 = threading.Thread(target=wait_for_event) thread2 = threading.Thread(target=wait_for_event) thread3 = threading.Thread(target=set_event) thread1.start() thread2.start() # Wait for few seconds to demonstrate the waiting threads time.sleep(2) thread3.start()
import threading event = threading.Event() def wait_for_event_timeout(): print("Waiting for event with timeout") event_is_set = event.wait(2) if event_is_set: print("Event has been set, proceed with execution") else: print("Timeout occurred, proceed with execution anyways") def set_event(): print("Setting the event") event.set() thread1 = threading.Thread(target=wait_for_event) thread2 = threading.Thread(target=wait_for_event_timeout) thread3 = threading.Thread(target=set_event) thread1.start() thread2.start() # Wait for few seconds to demonstrate the waiting threads time.sleep(2) thread3.start()This example demonstrates how a thread can wait for an event with a timeout. The `wait_for_event_timeout()` function waits for the event to be set using the `event.wait(timeout)` method. If the timeout occurs, the function proceeds with execution instead of waiting indefinitely. The threading module is part of Python's standard library, so no installation is required.