Search code examples
pythonmultithreadingeventssleep

Best way to wake a sleeping thread?


There's an instrument on my LAN that sends a UDP data packet every 5-10 ms. In my application, I have a reader thread that allocates a socket with a large buffer when it starts, then enters an infinite loop to read the accumulated packets, parse them, write them to a spooler, then sleep for half a second (time.sleep(0.500)).

I have several lazy consumers for the data, most of which do archiving or generate passive statistics. But one consumer (for display) needs up-to-the-moment data, and needs to wake the sleeping reader (to read the socket) before querying the spooler.

What is the best way to wake a sleeping thread?

(Or, alternately, is there a better way for a thread to sleep that's easier to wake?)


Solution

  • I had failed to notice that threading.condition.wait() has an optional timeout argument!

    The answer is to create a condition object and use its wait() method with the optional timeout instead of time.sleep(). If the thread needs to be woken prior to the timeout, call the notify() method of the condition object.