0
0
PythonHow-ToBeginner · 3 min read

How to Use Event in Python Threading for Thread Communication

In Python threading, use the Event class to create a simple flag that threads can wait for or set to communicate. Threads call event.wait() to pause until another thread calls event.set(), signaling them to continue.
📐

Syntax

The Event class in the threading module provides a simple way to communicate between threads using a flag.

  • event = threading.Event(): Creates a new event object.
  • event.wait(timeout=None): Blocks the calling thread until the event is set or timeout occurs.
  • event.set(): Sets the event flag to true, waking all waiting threads.
  • event.clear(): Resets the event flag to false, causing threads to wait again.
  • event.is_set(): Returns True if the event flag is set, else False.
python
import threading

event = threading.Event()

# Thread waits for event
# event.wait(timeout=None)

# Thread signals event
# event.set()

# Reset event
# event.clear()

# Check event status
# event.is_set()
💻

Example

This example shows two threads: one waits for an event to be set, and the other sets the event after a delay. The waiting thread resumes when the event is set.

python
import threading
import time

def waiter(event):
    print("Thread waiting for event...")
    event.wait()  # Wait until event is set
    print("Event detected! Thread resuming work.")

def setter(event):
    print("Setter thread sleeping for 3 seconds...")
    time.sleep(3)
    event.set()  # Signal the event
    print("Setter thread set the event.")

# Create an Event object
event = threading.Event()

# Create threads
thread1 = threading.Thread(target=waiter, args=(event,))
thread2 = threading.Thread(target=setter, args=(event,))

# Start threads
thread1.start()
thread2.start()

# Wait for threads to finish
thread1.join()
thread2.join()
Output
Thread waiting for event... Setter thread sleeping for 3 seconds... Setter thread set the event. Event detected! Thread resuming work.
⚠️

Common Pitfalls

Common mistakes when using Event include:

  • Calling event.wait() without a timeout can block forever if set() is never called.
  • Forgetting to call event.clear() if you want to reuse the event for multiple wait cycles.
  • Assuming event.set() wakes only one thread; it wakes all waiting threads.
python
import threading
import time

event = threading.Event()

def wrong_wait():
    print("Waiting without timeout...")
    event.wait()  # May block forever if event is never set
    print("This may never print if event is not set.")

def correct_wait():
    print("Waiting with timeout of 2 seconds...")
    if event.wait(timeout=2):
        print("Event set!")
    else:
        print("Timeout expired, event not set.")

# Demonstrate wrong and correct usage
thread_wrong = threading.Thread(target=wrong_wait)
thread_correct = threading.Thread(target=correct_wait)

thread_wrong.start()
thread_correct.start()

# Set event after 1 second
time.sleep(1)
event.set()

thread_wrong.join()
thread_correct.join()
Output
Waiting without timeout... Waiting with timeout of 2 seconds... Event set! This may never print if event is not set.
📊

Quick Reference

MethodDescription
Event()Create a new event object
wait(timeout=None)Block until event is set or timeout expires
set()Set the event flag, waking all waiting threads
clear()Reset the event flag to false
is_set()Check if the event flag is set

Key Takeaways

Use threading.Event() to create a flag for thread communication.
Call event.wait() in threads that should pause until signaled.
Call event.set() to wake all waiting threads.
Remember to clear the event with event.clear() if reusing it.
Use timeouts in wait() to avoid indefinite blocking.