Is an event loop just a for/while loop with optimized polling?

Posted by Alan on Programmers See other posts from Programmers or by Alan
Published on 2013-10-18T20:03:37Z Indexed on 2013/10/18 22:15 UTC
Read the original article Hit count: 242

I'm trying to understand what an event loop is. Often the explanation is that in the event loop, you do something until you're notified that an event occurred. You than handle the event and continue doing what you did before.

To map the above definition with an example. I have a server which 'listens' in a event loop, and when a socket connection is detected, the data from it gets read and displayed, after which the server goes to the listening it did before.


However, this event happening and us getting notified 'just like that' are to much for me to handle. You can say: "It's not 'just like that' you have to register an event listener". But what's an event listener but a function which for some reason isn't returning. Is it in it's own loop, waiting to be notified when an event happens? Should the event listener also register an event listener? Where does it end?


Events are a nice abstraction to work with, however just an abstraction. I believe that in the end, polling is unavoidable. Perhaps we are not doing it in our code, but the lower levels (the programming language implementation or the OS) are doing it for us.

It basically comes down to the following pseudo code which is running somewhere low enough so it doesn't result in busy waiting:

while(True):
    do stuff
    check if event has happened (poll)
    do other stuff

This is my understanding of the whole idea, and i would like to hear if this is correct. I am open in accepting that the whole idea is fundamentally wrong, in which case I would like the correct explanation.

Best regards

© Programmers or respective owner

Related posts about design

Related posts about programming-languages