Python threading Event Class

The threading.Event class in Python's threading module provides a simple mechanism for signaling between threads. It allows one or more threads to wait until they are notified that an event has occurred.

Table of Contents

  1. Introduction
  2. threading.Event Class Syntax
  3. Examples
    • Basic Usage
    • Using Event to Control Threads
    • Using Event with Timeout
  4. Real-World Use Case
  5. Conclusion

Introduction

The threading.Event class is used to manage an internal flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is set to true. This can be useful for coordinating the start and stop of threads or other synchronization needs.

threading.Event Class Syntax

Here is how you create and use an event with the threading.Event class:

import threading

event = threading.Event()

Methods:

  • set(): Set the internal flag to true. All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block.
  • clear(): Reset the internal flag to false. Subsequently, threads calling wait() will block until set() is called again.
  • wait(timeout=None): Block until the internal flag is true. If the internal flag is true on entry, return immediately. If the internal flag is false, block until another thread calls set() or until the optional timeout occurs.
  • is_set(): Return true if and only if the internal flag is true.

Examples

Basic Usage

Create and use an event to synchronize threads.

Example

import threading
import time

event = threading.Event()

def worker():
    print("Worker waiting for event to be set")
    event.wait()
    print("Worker received event")

thread = threading.Thread(target=worker)
thread.start()

time.sleep(2)
print("Main thread setting event")
event.set()
thread.join()

Using Event to Control Threads

Use an event to start and stop a thread.

Example

import threading
import time

event = threading.Event()

def worker():
    while not event.is_set():
        print("Worker is running")
        time.sleep(1)
    print("Worker stopping")

thread = threading.Thread(target=worker)
thread.start()

time.sleep(5)
print("Main thread stopping worker")
event.set()
thread.join()

Using Event with Timeout

Use an event with a timeout to control how long a thread waits.

Example

import threading
import time

event = threading.Event()

def worker():
    while not event.wait(timeout=2):
        print("Worker is running")
    print("Worker stopping")

thread = threading.Thread(target=worker)
thread.start()

time.sleep(5)
print("Main thread stopping worker")
event.set()
thread.join()

Real-World Use Case

Synchronizing Multiple Threads

Use events to synchronize multiple threads.

Example

import threading
import time

start_event = threading.Event()
stop_event = threading.Event()

def worker(worker_id):
    start_event.wait()
    while not stop_event.is_set():
        print(f"Worker {worker_id} is running")
        time.sleep(1)
    print(f"Worker {worker_id} stopping")

threads = [threading.Thread(target=worker, args=(i,)) for i in range(3)]

for thread in threads:
    thread.start()

time.sleep(2)
print("Main thread starting all workers")
start_event.set()

time.sleep(5)
print("Main thread stopping all workers")
stop_event.set()

for thread in threads:
    thread.join()

Conclusion

The threading.Event class is used for managing signaling between threads in Python. It allows you to coordinate actions and synchronize the execution of multiple threads effectively. Proper usage can enhance the reliability and control of your multithreaded applications.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare