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?)
We can wake the thread by calling either the notify() or notifyAll() methods on the monitor that is being waited on. Use notifyAll() instead of notify() when you want to wake all threads that are in the waiting state.
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.
interrupt() method: If any thread is in sleeping or waiting for a state then using the interrupt() method, we can interrupt the execution of that thread by showing InterruptedException. A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class.
If it is a UI worker thread, as long as they have some kind of progress indicator, anywhere up to half a second should be good enough. The UI should be responsive during the operation since its a background thread and you definitely have enough CPU time available to check every 500 ms.
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.
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