Event loop¶
Category: Scheduling · Status: stub · Lessons: chapter 06, Async (planned)
One line: A loop on one thread that waits for events — a socket ready, a timer due, work finished — and runs the callbacks or resumes the tasks waiting on each.
Also called: run loop, message loop.
How it connects¶
flowchart LR
n_async_runtime["Async runtime (executor and reactor)"]
n_event_loop["Event loop"]
n_event_driven_programming["Event-driven programming"]
n_io_multiplexing["I/O multiplexing"]
n_async_runtime -->|uses| n_event_loop
n_event_driven_programming -->|uses| n_event_loop
n_event_loop -->|uses| n_io_multiplexing
classDef center stroke-width:3px
class n_event_loop center
classDef outside stroke-dasharray: 4 3
class n_async_runtime,n_event_driven_programming,n_io_multiplexing outside
- Is built on: I/O multiplexing
- Is used by: Async runtime (executor and reactor), Event-driven programming
- See also: Blocking the event loop, Callback, Concurrency models, Timers and tickers, UI thread
In each language¶
| Rust | None in the standard library; an async runtime such as Tokio ↗ provides it |
| C | Written by hand around poll ↗, or taken from an event library |
| Python | The asyncio event loop ↗; applications normally start it with asyncio.run and rarely touch the loop object |
| JavaScript | Always there, provided by the host; microtasks ↗ such as promise callbacks run before control returns to the event loop |
| Swift | RunLoop ↗ in Foundation |
| Erlang and Elixir | A GenServer ↗ is a process whose receive loop the behaviour writes for you |
Where to read more¶
- In the books: Asynchronous Programming in Rust, Carl Fredrik Samson — ch. 3, 'Understanding OS-Backed Event Queues, System Calls, and Cross-Platform Abstractions'
- In the books: asyncio Recipes, Mohamed Mustapha Tahrioui — ch. 2, 'Working with Event Loops'
- In the books: JavaScript Concurrency, Adam Boduch — ch. 8, 'Evented IO with NodeJS'
- In the books: Grokking Concurrency, Kirill Bobrov — ch. 11, 'Event-based concurrency' → 'Event loop'
- In the books: Python Concurrency with asyncio, Matthew Fowler — ch. 1, 'Getting to know asyncio' → 'How an event loop works'
- In the books: Using Asyncio in Python, Caleb Hattingh — ch. 3, 'Asyncio Walk-Through' → 'Event Loop'
- Notes: Event loop - async - general ↗
- Reference: Wikipedia: Event loop ↗