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 ;
until response arrived
is the key. What does that actually do? Is it a blocking call? – Acaleph