Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 627
Justinas Avatar asked Mar 03 '26 21:03

Justinas


1 Answers

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.

like image 106
Frédéric Hamidi Avatar answered Mar 06 '26 17:03

Frédéric Hamidi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!