Empty loop which waits for condition (busy-waiting)

Thomas White picture Thomas White · Jan 15, 2015 · Viewed 9.1k times · Source

I have been spending the last 20 minutes doing research on empty loops which purpose are only to wait for a condition to become true.

I have a function called "waitForLoaded" which is a thread created by CreateThread.

The function:

void waitForLoaded(){
    while(!isLoaded){
        Sleep(500); // < my question
    }
    Sleep(500); //sleep another 500ms to ensure everything is loaded.
    //continue on here
}

I am using Sleep(500) to be easy on the CPU as I believe that using either 0 or 1 would drain the processor.

I have seen in many peoples code "Sleep(0)" used and I never understood why not just no sleep at all and to do "while(condition){}.."

I can't find any solid answer on which is more CPU friendly so I am asking people here, what is the difference between busy-waiting with 0ms, 1ms or 500ms and which is more CPU friendly.

In my opinion it would be best to do at least a half sleep which is nearly unnoticeable by the user.

Answer

zdan picture zdan · Jan 15, 2015

On windows a Sleep(0) will not spend any time sleeping, but allows the OS to relinquish the CPU to another waiting thread. It's kind of like saying "If someone is waiting in line let them go ahead, otherwise I'd like to go right away."