Without polling how to make a Python thread wait a signal (like boolean switch) from another thread?
Sep 2, 10:57pm
To make a Python thread wait for a signal (like a boolean switch) from another thread without polling, you can use the threading.Event class. This is a synchronization primitive that allows one or more threads to wait until an event is set by another thread.
How It Works:
threading.Event: This object provides a simple way for threads to communicate. One thread can set the event, and other threads can wait for it to be set.
No Polling: Threads waiting for the event will block until the event is set, avoiding the inefficiency of polling.
Example Code:
Here’s how you can implement it:
python
import threading
import time
# Create an Event object
event = threading.Event()
def worker_thread():
print("Worker thread: Waiting for the signal...")
# Wait for the event to be set
event.wait()
print("Worker thread: Received the signal! Continuing...")
def main_thread():
print("Main thread: Starting worker thread...")
worker = threading.Thread(target=worker_thread)
worker.start()
# Simulate some work in the main thread
time.sleep(2)
print("Main thread: Sending the signal!")
# Set the event to signal the worker thread
event.set()
worker.join()
print("Main thread: Worker thread has finished.")
# Run the main thread
main_thread()
Explanation:
event = threading.Event(): Creates an Event object.
event.wait(): The worker thread calls this method and blocks until the event is set.
event.set(): The main thread sets the event, which unblocks the worker thread.
Key Points:
Efficiency: No CPU cycles are wasted on polling.
Thread Safety: The Event object is thread-safe and handles synchronization internally.
Reusability: You can reset the event with event.clear() if needed.
Sep 2, 10:57pm
This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.