Search code examples
c++multithreadingthread-synchronization

Why does this_thread::sleep_for not reduce CPU usage of while loop


I have a while loop as follows:

while(true){
    //do stuff
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

When I look at the CPU usage it is almost 100% ... is there any way to do something like this while preserving CPU cycles without having to use complicated condition variables?

EDIT: "do stuff" checks a queue to see if there are any events to send... if there are none, then it does nothing (super fast), otherwise it sends the events via HTTP. It is very rare to have an event (e.g once every 10 minutes).

I know you could re-write this to use a condition variable but I'd prefer to figure out why there is so much CPU usage.


Solution

  • I figured out the reason: During the logic of the code ("// do stuff") there was a continue statement. The continue statement caused the thread to skip over the sleep statement causing it to loop continuously. I moved the thread_sleep to the top of the while loop and the CPU usage went from 99% to 0.1%