Thread Signaling with threading.Event
`threading.Event` manages an internal flag. One thread can call `.wait()` to sleep until another thread calls `.set()`. It's the simplest cross-thread green-light signal 🚦.
import threading, time
ready_event = threading.Event()
def worker():
print("Worker waiting for green light... ⏳")
ready_event.wait() # Sleep until flag becomes True 🚦
print("Worker received signal and started! 🚀")
t = threading.Thread(target=worker)
t.start()
time.sleep(0.01)
ready_event.set() # Unblocks all waiting threads!
t.join()
# 56. Thread Signaling with threading.Event `threading.Event` manages an internal flag. One thread can call `.wait()` to sleep until another thread calls `.set()`. It's the simplest cross-thread green-light signal 🚦. ```python import threading, time ready_event = threading.Event() def worker(): print("Worker waiting for green light... ⏳") ready_event.wait() # Sleep until flag becomes True 🚦 print("Worker received signal and started! 🚀") t = threading.Thread(target=worker) t.start() time.sleep(0.01) ready_event.set() # Unblocks all waiting threads! t.join() ``` To reuse an event, call `ready_event.clear()` to reset the flag back to `False`. Multiple threads can wait on the same event simultaneously! 🚦 --- ### Question Which method unblocks all threads sleeping on `event.wait()`? 🧠 - [ ] a. `event.set()` 🚦 - [ ] b. `event.notify()` - [ ] c. `event.wake()` - [ ] d. `event.resume()` --- ### Challenge Import `threading`. Create `event = threading.Event()`. Print `event.is_set()`. Call `event.set()`. Print `event.is_set()`. 🎯 <details> <summary>Solution</summary> ```python import threading event = threading.Event() print(event.is_set()) event.set() print(event.is_set()) ``` </details>