Waiting on multiple Event objects in Python 3

Passive waiting is a way of suspending programs execution without consuming any CPU (in contrast with active waiting where a program is busy doing nothing). In Python, you can use certain classes from the threading module (such as Condition and Event). Let's take for example the Event class. It is good for waiting for an event. But what if you need to wait for many events? You might say "Why not to make a list of multiple Event objects and wait for all of them?" Well... that is not going to work:

There are two problems with this kind of code:

  • If you use any timeout value, you degrade it to active wait (and you will also wait until the last event in the list gets activated or times out).
  • If you don't use a timeout value, the code gets stuck on the first event (and then the second, third, etc.).

If you used to program in C/C++, you might want to use a select function. Select allows you to wait for several I/O operations and returns when any of them ends. The good news is there is such a function in Python 3. Concretely, it is the select method of the selectors.BaseSelector class. The bad news is you can wait only on file objects.

I don't know how about you but I'd like to wait on other things, such as MULTIPLE EVENT OBJECTS! But you can't, because those are not file objects. Now you might be saying

“I wish there was a way to wait on those bloody Event objects.”

Well... there is :-). Here's a slightly modified code, so it works in Python 3 (origin is here):

To wait for multiple event objects using the select method is simple as this:

Any suggestions or improvements? Leave a comment below :-).

Zanechte komentář / Leave a comment

Your email address will not be published. Required fields are marked *