Sujet : Re: How to break while loop based on events raised in a thread (Python 2.7)
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.pythonDate : 27. Nov 2024, 15:19:25
Autres entêtes
Organisation : Stefan Ram
Message-ID : <event-20241127151444@ram.dialup.fu-berlin.de>
References : 1
marc nicole <
mk1853387@gmail.com> wrote or quoted:
Subject: How to break while loop based on events raised in a
thread (Python 2.7)
`Threading.Event` is your go-to for thread communication without
breaking a sweat.
It's a synchronization primitive that lets threads chat with
each other using a simple flag mechanism. Think of it as a
traffic light for your threads.
Here's the lowdown:
Creating an event:
import threading
event = threading.Event()
. Checking if the event is set:
if event.is_set():
print( "Green light, go!" )
. Setting the event (turning the light green):
event.set()
. Clearing the event (back to red):
event.clear()
. Waiting for the event to be set:
event.wait() # Will chill here until the event is set
. Waiting with a timeout (for the impatient threads):
if event.wait(timeout=5):
print( "Event was set within 5 seconds" )
else:
print( "Timed out, event wasn't set" )
. The cool thing about `threading.Event` is that it's like a bouncer
at a club. One thread can be the bouncer (setting or clearing the
event), while other threads wait in line (using `wait()`). When the
bouncer gives the green light, all waiting threads get to party.
Here's a quick example to tie it all together:
import threading
import time
def waiter( event, name ):
print( f"{name} is waiting for the event" )
event.wait()
print( f"{name} received the event signal!" )
def main():
event = threading.Event()
# Create some threads that wait for the event
threading.Thread( target=waiter, args=( event, "Thread 1" )).start()
threading.Thread( target=waiter, args=( event, "Thread 2" )).start()
print( "Main thread: Chilling for 3 seconds before setting the event" )
time.sleep( 3 )
print( "Main thread: Setting the event!" )
event.set()
if __name__ == "__main__":
main()
. This script is like throwing a surprise party. The main
thread is setting up, while the other threads are waiting
outside. When everything's ready, the main thread yells
"Surprise!" (sets the event), and everyone rushes in.
Remember, `threading.Event` is your friend when you need
simple thread synchronization without the complexity of locks
or semaphores. It's perfect for those "wait until I say go"
scenarios in your multi-threaded Python fiesta.