高效的事件循环实现?
可能的重复:
您将如何实现基本的事件循环?
并非如此特定于语言的问题。事件循环的有效实现是什么?到目前为止,我只遇到过这样的事情:
while (true) {
handleEvents();
sleep(100);
}
我认为这不是最好的方法 - 如果睡眠持续时间太短,它会消耗大量CPU,如果睡眠时间太长,应用程序将非常无响应。
那么,有没有更好的办法呢?
谢谢
Possible Duplicate:
How would you implement a basic event-loop?
Not really a language-specific question. What could be an efficient implementation of event loop? So far I've only encountered something like this:
while (true) {
handleEvents();
sleep(100);
}
which I don't think is the best way - if sleep duration is too short, it will eat lots of cpu, and if it's too long, the app will be pretty unresponsive.
So, is there a better way?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最常见的模式是:
WaitForNextEvent()
返回false
表示没有更多事件需要处理,最重要的是,能够执行阻塞等待下一个事件。例如,事件源可能是文件、套接字、线程的消息队列或另一个 可等待对象。在这种情况下,您可以保证
HandleEvent()
仅在事件就绪时运行,并在事件就绪后立即触发。The most common pattern is:
With
WaitForNextEvent()
returningfalse
to indicate there are no more events to process, and, most importantly, being able to perform a blocking wait for the next event.For instance, the event source might be a file, a socket, the thread's message queue or another waitable object of some kind. In that case, you can guarantee that
HandleEvent()
only runs if an event is ready, and is triggered very shortly after an event becomes ready.