Thom Nichols


Technology is evolution outside the gene pool

Use Python's threading.Event for interruptable sleep

As I've mentioned before, python's lack of a Thread.interrupt() method makes writing lively concurrent programs sometimes difficult.  One of the most common scenarios is when you want to sleep() for a period of time.  Yes, sometimes polling is the answer.  There are times when you really want to say "wait for some period of time..."   Except what you almost always mean is "wait for some period of time, unless some condition occurs like a shutdown.  That "unless" can be a real bugger -- imagine you want to shut down or perform some other operation but you've got some damn thread in the middle of a sleep().

Thankfully, in almost every situation, sleep() can be replaced with a threading.EventEvent.wait() says, "sleep for x seconds, unless someone else calls Event.set()."  Perfect!  Now I can sleep without causing threads to be unresponsive. 

I should note, It's also often useful to determine whether you've actually waited for the entire duration or if Event.set() interrupted that action.  Well, in Python 2.6, the return value from Event.wait() doesn't indicate whether a timeout occurred or not.  Thankfully, this was fixed in 2.7.

Now go fix your unresponsive code!  :-)

Category: Python concurrency