Sleep()是邪恶的吗? [英] Is Sleep() evil?

查看:89
本文介绍了Sleep()是邪恶的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,在许多情况下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:我问这个问题是因为

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆