Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python threading: will Event.set() really notify every waiting thread

Tags:

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:

  • Can I be ABSOLUTELY sure that all the waiting thread(s) will be notified? (i.e. Event.set() "notifies" the threads)
  • Or could it happen that those two lines are executed so quickly after each other, that some threads might still be waiting? (i.e. Event.wait() polls the event's state, which might be already "cleared" again)

Thanks for your answers!

like image 667
Criss Avatar asked Jun 06 '11 16:06

Criss


1 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) 
like image 96
Cédric Julien Avatar answered Oct 07 '22 19:10

Cédric Julien