Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

language agnostic - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...