If I have a threading.Event
and the following two lines of code:
event.set() event.clear()
and I have some threads who are waiting for that event.
My question is related to what happens when calling the set()
method:
Event.set()
"notifies" the threads)Event.wait()
polls the event's state, which might be already "cleared" again)Thanks for your answers!
In the internals of Python, an event is implemented with a Condition()
object.
When calling the event.set()
method, the notify_all()
of the condition is called (after getting the lock to be sure to be not interrupted), then all the threads receive the notification (the lock is released only when all the threads are notified), so you can be sure that all the threads will effectively be notified.
Now, clearing the event just after the notification is not a problem.... until you do not want to check the event value in the waiting threads with an event.is_set()
, but you only need this kind of check if you were waiting with a timeout.
Examples :
pseudocode that works :
#in main thread event = Event() thread1(event) thread2(event) ... event.set() event.clear() #in thread code ... event.wait() #do the stuff
pseudocode that may not work :
#in main thread event = Event() thread1(event) thread2(event) ... event.set() event.clear() #in thread code ... while not event.is_set(): event.wait(timeout_value) #do the stuff
Edited : in python >= 2.7 you can still wait for an event with a timeout and be sure of the state of the event :
event_state = event.wait(timeout) while not event_state: event_state = event.wait(timeout)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With