About
An Event loop 1) is a thread that waits for and dispatches events or messages that may contains:
- data
- or runnable code
An event loop is also known as:
- message dispatcher,
- message loop,
- message pump,
- or run loop
When the event loop in a event-driven system is the entry point, it's referred to:
- the main loop
- or main event loop.
because it runs on the main thread.
They are responsible for:
- executing the code,
- collecting and processing events,
- and executing queued sub-tasks
Each event shall be processed in a reasonable amount of time to not block the event loop. This means that thread-blocking operations shall not be performed while executed on the event loop, exactly like processing events in a graphical user interface (e.g., freezing a Java / Swing interface by doing a slow network request).
An events can be :
It is almost non-blocking (of kernel threads) allowing it to handle a lot of concurrency (e.g. handle many connections, or messages) using a very small number of kernel threads, which allows it to scale very well.
Features
Event loops are used to implement:
- asynchronous programming models. The asynchronous functons are put in the queue.
Example
This is how asynchrony is implemented:
- in other reactive framework such as Java - Vert.X Framework
Implementation
The event loop got its name from it's minimal implementation:
while (queue.waitForMessage()) {
queue.processNextMessage()
}
where queue
The event loop works by:
- making a request to some internal or external event provider (that generally blocks the request until an event has arrived),
- then calls the relevant event handler (“dispatches the event”).