Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Sleep() evil?

First of all, there are many cases where Sleep() is misused, for example to "synchronize" threads or to regularily poll a value where a notification function would do (In Win32 WaitForSingleObject for example)

But what about other use cases? Is Sleep always evil? If no, what are good use cases for Sleep? If yes, why do almost all languages have some kind of Sleep statement?

PS: I've asked this question because of one of the comments of another question. There the OP states, that in his opinion, Sleep is to be avoided like goto.

like image 857
Daniel Rikowski Avatar asked Jul 08 '09 08:07

Daniel Rikowski


People also ask

What is sleep () in C?

The function sleep gives a simple way to make the program wait for a short interval. If your program doesn't use signals (except to terminate), then you can expect sleep to wait reliably throughout the specified interval.

Should thread sleep be used?

One of the way to achieve synchronization, implement wait is by calling Thread. sleep() function however, it is not recommended because this is not very stable and unreliable. The time has to be specified in milliseconds.

What does sleep mean in code?

In computing, sleep is a command in Unix, Unix-like and other operating systems that suspends program execution for a specified time.

Why do we use sleep function?

Sleep is an essential function1 that allows your body and mind to recharge, leaving you refreshed and alert when you wake up. Healthy sleep also helps the body remain healthy and stave off diseases. Without enough sleep, the brain cannot function properly.


1 Answers

I actually believe the assertion you linked is correct. The problem is sleep is being used (as you noted) as an inefficient substitute for notification mechanisms. Sleep is always inferior to a properly implemented notification mechanism, If you are waiting for an event. If you actually need to wait a specific amount of time for something, then sleep is appropriate.

For example, in some network protocols, you make use of a technique known as exponential backoff, where if you detect a collision on the network, you want to wait a random (and exponentially increasing) amount of time before you retry. In this case sleep is appropriate because you're not trying to wait for an event to happen, you're trying to wait for a specific amount of time to pass.

like image 192
Falaina Avatar answered Oct 05 '22 07:10

Falaina