Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most CPU-efficient way to "waste time" in a thread?

I have a number of threads (100's) that each execute for a few seconds at a time. When they are executing, they spend a significant amount of that time waiting for a response from another system (a serial device). I am mindful that having 100 threads executing at once could be a resource hog so I actually limit the number of threads that can start at any one time.

It occurs to me though that there must be good and bad ways of waiting for an external event inside a thread. Is this approach CPU-intensive?:

send command ;
repeat
until response arrived ;
process response ;    

and does this approach make it more efficient?:

send command ;
repeat
    Sleep (20) ;
until response arrived ;
process response ;  

* ADDITIONAL INFO *

The environment is x86 Windows XP. The thread code is a long and involved series of interactions with a serial device but in general, it consists of writing characters to a COM port (using the AsyncFree serial library) and waiting for characters to be returned by camping on the incoming characters buffer and processing them when they arrive. I imagine the serial library makes device reads and writes. The time in the thread can be as long as a minute , or as short as a couple of seconds, but most of that time is spent waiting for characters to leave the port, or waiting for the response characters (baud rate is slow), hence my question about the best way for the thread to behave while it is waiting. Currently I am calling Sleep in a loop waiting for CharactersInBuffer to become non-zero, processing each character when it arrives, and exiting the thread when I have the complete response. So the code looks more like (ignoring handling of timeouts, etc):

send command ;
Packet = '' ;
repeat

    repeat
        Sleep (20) ;
    until response character arrived ;
    build Packet

until complete packet arrived
process response ;  
like image 467
rossmcm Avatar asked Nov 01 '11 19:11

rossmcm


1 Answers

If the thread is truly waiting with something like a WaitForSingleObject, which uses no processor time, then times out, there is no reason to put a delay in the thread with sleep.

Your user isn't waiting on the thread to be responsive, it's not using processor time, and other threads won't be blocked, so there would be no reason to put the thread to sleep.

As David Heffernan indicated in his comment, if it's not using 100% of your CPU now, then there's no problem.

You might use sleep() if you were single threaded and you had to occasionally respond to the user in between waiting on the serial port to respond.

Also, having a thread sleep would not make it more efficient. It would simply yield processor cycles to other threads.

Take a look at sleep(0) as a CPU efficient way of "wasting time" in a thread.

like image 117
Marcus Adams Avatar answered Oct 27 '22 05:10

Marcus Adams