In Python, the threading
module provides the Event
class, which is a synchronization primitive that allows one or more threads to wait for an event to be set by another thread. The basic idea is that one thread signals an event, and other threads wait for that event to occur. Here’s a simple explanation with an example:
import threading
import time
# Create an Event object
event = threading.Event()
# Function that waits for the event to be set
def wait_for_event():
print("Thread A is waiting for the event to be set.")
event.wait() # Blocks until the event is set
print("Thread A received the event.")
# Function that sets the event after a delay
def set_event_after_delay():
print("Thread B is sleeping for 2 seconds.")
time.sleep(2)
event.set() # Sets the event, allowing Thread A to proceed
# Create two threads
thread_A = threading.Thread(target=wait_for_event)
thread_B = threading.Thread(target=set_event_after_delay)
# Start the threads
thread_A.start()
thread_B.start()
# Wait for both threads to finish
thread_A.join()
thread_B.join()
In this example, Thread A
is waiting for the event (event.wait()
), and Thread B
sets the event after sleeping for 2 seconds (event.set()
). The Event
object is used to synchronize the two threads.
Output Explanation:
Thread A is waiting for the event to be set.
Thread B is sleeping for 2 seconds.
Thread A received the event.
Thread A starts waiting for the event.
Thread B sleeps for 2 seconds and then sets the event.
Thread A receives the event and continues its execution.
This example demonstrates a basic scenario where one thread is waiting for an event to be set by another thread. In a more complex application, events are often used to coordinate activities among multiple threads, ensuring that certain conditions are met before proceeding.