Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?)

like image 708
BobC Avatar asked Apr 03 '14 21:04

BobC


People also ask

How do you wake up a sleeping thread?

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.

How do you wake up a sleeping thread python?

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.

How do I stop sleeping thread?

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.

How long should a thread sleep?

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.


1 Answers

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.

like image 172
BobC Avatar answered Oct 13 '22 22:10

BobC