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
.
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.
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.
In computing, sleep is a command in Unix, Unix-like and other operating systems that suspends program execution for a specified time.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With