轮询还是等待更好? [英] Is it better to poll or wait?

查看:286
本文介绍了轮询还是等待更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到一个问题,为什么轮询不好".就最大程度地减少一个线程使用的处理器时间而言,最好执行旋转等待(即轮询while循环中所需的更改)或等待内核对象(例如Windows中的内核事件对象) ?

I have seen a question on why "polling is bad". In terms of minimizing the amount of processor time used by one thread, would it be better to do a spin wait (i.e. poll for a required change in a while loop) or wait on a kernel object (e.g. a kernel event object in windows)?

对于上下文,假定需要代码在任何类型的处理器,单核,超线程,多核等处理器上运行.还要假定进行轮询或等待的线程无法继续进行,直到轮询结果令人满意为止如果它轮询而不是等待.最后,线程开始等待(或轮询)到满足条件之间的时间可能会从很短的时间变化到很长的时间.

For context, assume that the code would be required to run on any type of processor, single core, hyperthreaded, multicore, etc. Also assume that a thread that would poll or wait can't continue until the polling result is satisfactory if it polled instead of waiting. Finally, the time between when a thread starts waiting (or polling) and when the condition is satisfied can potentially vary from a very short time to a long time.

由于操作系统在等待"的情况下可能会更有效地轮询",因此我不希望看到等待只是意味着其他人在进行轮询"的说法,这已经是老新闻了,不一定100%准确.

Since the OS is likely to more efficiently "poll" in the case of "waiting", I don't want to see the "waiting just means someone else does the polling" argument, that's old news, and is not necessarily 100% accurate.

推荐答案

如果OS具备此类并发原语的合理实现,那么等待内核对象肯定会更好.

Provided the OS has reasonable implementations of these type of concurrency primitives, it's definitely better to wait on a kernel object.

在其他原因中,这使OS知道在等待对象处于适当状态之前,不要为其他时间片安排有关线程.否则,您的线程将不断被重新调度,上下文切换到该线程,然后运行一段时间.

Among other reasons, this lets the OS know not to schedule the thread in question for additional timeslices until the object being waited-for is in the appropriate state. Otherwise, you have a thread which is constantly getting rescheduled, context-switched-to, and then running for a time.

您特别询问了如何最小化线程的处理器时间:在本示例中,在内核对象上进行线程阻塞将使用零时间.轮询线程将花费各种时间.

You specifically asked about minimizing the processor time for a thread: in this example the thread blocking on a kernel object would use ZERO time; the polling thread would use all sorts of time.

此外,其他人正在轮询"参数不一定是正确的.当内核对象进入适当的状态时,内核可以在那一瞬间查看哪些线程正在等待该对象……然后调度其中一个或多个线程以供执行.在这种情况下,内核(或其他任何人)都不需要轮询任何东西.

Furthermore, the "someone else is polling" argument needn't be true. When a kernel object enters the appropriate state, the kernel can look to see at that instant which threads are waiting for that object...and then schedule one or more of them for execution. There's no need for the kernel (or anybody else) to poll anything in this case.

这篇关于轮询还是等待更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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