Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 599
urig Avatar asked Jul 08 '14 11:07

urig


People also ask

Is Python sleep busy waiting?

The sleep function is an OS call that differs from busy wait in that it doesn't block the thread. If you have a multi-threaded script though, it shouldn't block the other threads.

What happens when a thread sleeps?

Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

Why thread sleep is not recommended?

Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.

What is difference between sleep () and wait ()?

Wait() method releases lock during Synchronization. Sleep() method does not release the lock on object during Synchronization. Wait() should be called only from Synchronized context. There is no need to call sleep() from Synchronized context.


2 Answers

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.

like image 118
Jim Mischel Avatar answered Oct 03 '22 06:10

Jim Mischel


When your code is sleeping for a moment, technically it will be in sleep state freeing up a CPU. While in busy waiting your code is holding the CPU until condition is met.

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

It is not busy waiting, rather polling which is more performant that busy waiting. There is a difference between both

Simply put, Busy-waiting is blocking where as Polling is non-blocking.

like image 22
srk Avatar answered Oct 03 '22 06:10

srk