Search code examples
c#multithreadingthread-sleep

Is it Really Busy Waiting If I Thread.Sleep()?


My question is a bit nit-picky on definitions:

Can the code below be described as "busy waiting"? Despite the fact that it uses Thread.Sleep() to allow for context switching?

while (true) {
    if (work_is_ready){
        doWork();
    }
    Thread.Sleep(A_FEW_MILLISECONDS);
}

PS - The current definition for busy waiting in Wikipedia suggests that it is a "less wasteful" form of busy waiting.


Solution

  • Any polling loop, regardless of the time between polling operations, is a busy wait. Granted, sleeping a few milliseconds is a lot less "busy" than no sleep at all, but it still involves processing: thread context switches and some minimal condition checking.

    A non-busy wait is a blocking call. The non-busy version of your example would involve waiting on a synchronization primitive such as an event or a condition variable. For example, this pseudocode:

    // initialize an event to be set when work is ready
    Event word_is_ready;
    work_is_ready.Reset();
    
    // in code that processes work items
    while (true)
    {
        work_is_ready.Wait();  // non-busy wait for work item
        do_work();
    }
    

    The difference here is that there is no periodic polling. The Wait call blocks and the thread is never scheduled until the event is set.