In my experience, you should do something that refuses the processor. sleep works fine, and on most Windows systems, even sleep (1) is enough to completely offload the processor in a loop.
You can get the best of all worlds, however, if you use something like std :: condition_variable. You can create constructs using condition variables (similar to "events" and WaitForSingleObject in the Windows API).
One thread can block a condition variable that is freed by another thread. Thus, one thread can execute condition_varaible.wait (some_time), and it will either wait for a waiting period (without loading the processor), or it will continue to execute immediately when another thread releases it.
I use this method when one thread sends messages to another thread. I want the receiving stream to respond as soon as possible, and not after waiting for sleep (20) to complete. For example, the receiving stream has the condition condition_variable.wait (20). The sending stream sends the message and fulfills the corresponding condition_variable.release (). The receiving stream will immediately release and process the message.
This solution gives a very quick response to messages and does not require excessive processor load.
If you don't care about portability and you use windows, events and WaitForSingleObject do the same.
your loop will look something like this:
while(!done) { cond_var.wait(std::chrono::milliseconds(20)); // process messages... msg = dequeue_message(); if(msg == done_message) done = true; else process_message(msg); }
In another thread ...
send_message(string msg) { enqueue_message(msg); cond_var.release(); }
Your message processing loop will spend the most if it doesn't work, expecting a condition variable. When a message is sent and the condition variable is freed by the send stream, your receive stream immediately responds.
This allows your thread to receive a loop at the minimum speed specified by the wait time and the maximum value determined by the transmit stream.