Sleep()是邪恶的吗? [英] Is Sleep() evil?
问题描述
首先,在许多情况下Sleep()
被滥用,例如同步"线程或定期轮询通知功能可以执行的值(在Win32 WaitForSingleObject
中例如)
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)
但是其他用例呢? Sleep
总是邪恶的吗??如果不是,那么Sleep
的良好用例是什么?如果是,为什么几乎所有语言都具有某种Sleep
语句?
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
.
推荐答案
我实际上认为您链接的断言是正确的.问题是睡眠(如您所述)被用作通知机制的低效替代品.睡眠总是劣于正确实施的通知机制,如果您正在等待事件.如果您实际上需要等待特定时间,那么睡觉就可以了.
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.
这篇关于Sleep()是邪恶的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!