Search code examples
language-agnosticloopstwistedblockingnonblocking

how does a non-blocking event loop work?


Twisted has a "non-blocking" event loop.

I understand what a blocking event loop does (sort of, from the Wikipedia page) but can't figure out how a non-blocking one does.


Solution

  • while (true)
        wait_for_events
        handle_events
    

    Basically, non-blocking event loop utilizes device that allows for waiting for multiple events simultaneously (select/poll on UNIX, WaitForMultipleEvents on Windows, epoll on Linux kqueue on FreeBSD etc). In each iteration of main loop, events (file descriptors, timers etc) are registered in some kind of handle. Then, a function that waits for events (eg. select) is invoked. This typically returns all events that happened during invocation of that function. Finally, loop handles that events - typically by invoking callbacks associated with events.

    For details, see implementation of libevent or some GUI toolkit event loops - GTK+ or Qt.