An efficient event loop implementation? [duplicate]
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.
精彩评论