开发者

An efficient event loop implementation? [duplicate]

开发者 https://www.devze.com 2023-03-19 05:31 出处:网络
This q开发者_如何学运维uestion already has answers here: Closed 11 years ago. Possible Duplicate:
This q开发者_如何学运维uestion already has answers here: Closed 11 years ago.

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


The most common pattern is:

while (WaitForNextEvent()) {
    HandleEvent();
}

With WaitForNextEvent() returning false 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号