Programming Search⌘K

Patterncore

Event loop

Also called main loop, main event loop, message loop, message pump, message dispatcher, run loop.

An event loop is one thread that takes events and callbacks from a queue and runs each one to the end. It handles many tasks without locks, if no callback blocks the loop.

Family
concurrency
Intent
Handle many independent events on one thread by putting their handlers on a queue and running the handlers one at a time, each to its end, so that the handlers do not need locks.
Also called
Main loop, Message loop, Message pump

Intent

An event loop is an algorithm that continually dispatches control flow for events: the loop requests the next event from an event provider, and when an event is received, invokes its associated event handler.1 When the event loop is the central event dispatcher of a program, it is called the main loop or main event loop.1 Because one thread runs all the handlers, the handlers do not need locks to share data.

Problem

A program waits for many things at the same time: user input, timers, network replies and files. A thread for each wait uses memory, and threads that share data need locks. A program that waits for one thing at a time cannot respond to the others while it waits.

Solution

Put the code that handles each event in a callback, and put the callbacks on a queue. One thread runs a loop. In each turn, it takes the callbacks that are ready and runs each one to its end. When no callback is ready, the loop waits for the next event or the next timer.

        ┌──────────────── one thread ────────────────┐
        │  ┌─► wait for I/O or the next timer         │
 timers ┼─►│   move due timers to the ready queue     │
 I/O    ┼─►│   run each ready callback to its end ──┐ │
        │  └────────────── next turn ◄──────────────┘ │
        └─────────────────────────────────────────────┘

In JavaScript, the code that handles the completion of an asynchronous action is a callback, and this callback defines a job, which gets placed into a job queue once the action is completed.2 When a job is executed, it may create more jobs, which are added to the end of the queue.2 Each job is processed completely before any other job is processed, so a function cannot be preempted and runs entirely before any other code runs.2 In asyncio, callbacks that loop.call_soon() schedules are called in the order in which they are registered, at the next iteration of the event loop.4

The loop does not do slow I/O itself. Node.js performs non-blocking I/O operations, although a single JavaScript thread is used by default, by offloading operations to the system kernel whenever possible; when one of these operations completes, the kernel tells Node.js so that the callback can be added to the poll queue.3

Example

The program builds a small event loop with a queue of ready callbacks and a list of timers. It adds two timers, then two callbacks. The first callback adds a third callback, which waits for the next turn. When no callback is ready, the loop moves its clock to the next timer. A real loop sleeps or waits for I/O at that point; this clock is a counter, so the output does not depend on the speed of the machine.

order of the callbacks:
  time 0: first callback
  time 0: second callback
  time 0: callback that the first callback added
  time 10: timer of 10
  time 20: timer of 20
turns of the loop: 4

The examples for each language show the same program.

PythonGitHub
import heapq
from collections import deque


class EventLoop:
    """One thread takes ready callbacks from a queue and runs each one to the end."""

    def __init__(self):
        self.ready = deque()  # callbacks to run in this turn or the next
        self.timers = []  # heap of (due time, order, callback)
        self.now = 0  # a counter clock, so the output does not depend on the machine
        self.order = 0
        self.turns = 0

    def call_soon(self, callback):
        self.ready.append(callback)

    def call_later(self, delay, callback):
        self.order += 1
        heapq.heappush(self.timers, (self.now + delay, self.order, callback))

    def run(self):
        while self.ready or self.timers:
            if not self.ready:
                self.now = self.timers[0][0]  # a real loop sleeps or waits for I/O here
            while self.timers and self.timers[0][0] <= self.now:
                self.ready.append(heapq.heappop(self.timers)[2])
            self.turns += 1
            for _ in range(len(self.ready)):  # callbacks added now wait for the next turn
                self.ready.popleft()()


loop = EventLoop()
log = []


def say(text):
    def callback():
        log.append(f"time {loop.now}: {text}")
    return callback


def first():
    say("first callback")()
    loop.call_soon(say("callback that the first callback added"))


loop.call_later(20, say("timer of 20"))
loop.call_later(10, say("timer of 10"))
loop.call_soon(first)
loop.call_soon(say("second callback"))
loop.run()

print("order of the callbacks:")
for line in log:
    print(" ", line)
print("turns of the loop:", loop.turns)
Output
order of the callbacks:
  time 0: first callback
  time 0: second callback
  time 0: callback that the first callback added
  time 10: timer of 10
  time 20: timer of 20
turns of the loop: 4
  • Verdict: idiom. A small loop class with a deque of ready callbacks and a heapq of timers. In real code, asyncio gives loop.call_soon and loop.call_later.
#include <deque>
#include <functional>
#include <iostream>
#include <queue>
#include <string>
#include <tuple>
#include <vector>

// One thread takes ready callbacks from a queue and runs each one to the end.
class EventLoop {
public:
    using Callback = std::function<void()>;

    void call_soon(Callback callback) { ready_.push_back(std::move(callback)); }

    void call_later(int delay, Callback callback) {
        timers_.push({now_ + delay, ++order_, std::move(callback)});
    }

    void run() {
        while (!ready_.empty() || !timers_.empty()) {
            if (ready_.empty()) now_ = timers_.top().due;  // a real loop sleeps or waits for I/O here
            while (!timers_.empty() && timers_.top().due <= now_) {
                ready_.push_back(timers_.top().callback);
                timers_.pop();
            }
            turns_++;
            std::size_t count = ready_.size();  // callbacks added now wait for the next turn
            for (std::size_t i = 0; i < count; i++) {
                Callback callback = std::move(ready_.front());
                ready_.pop_front();
                callback();
            }
        }
    }

    int now() const { return now_; }
    int turns() const { return turns_; }

private:
    struct Timer {
        int due, order;
        Callback callback;
        bool operator>(const Timer& o) const { return std::tie(due, order) > std::tie(o.due, o.order); }
    };
    std::deque<Callback> ready_;  // callbacks to run in this turn or the next
    std::priority_queue<Timer, std::vector<Timer>, std::greater<Timer>> timers_;
    int now_ = 0;  // a counter clock, so the output does not depend on the machine
    int order_ = 0;
    int turns_ = 0;
};

int main() {
    EventLoop loop;
    std::vector<std::string> log;
    auto say = [&](std::string text) -> EventLoop::Callback {
        return [&, text] { log.push_back("time " + std::to_string(loop.now()) + ": " + text); };
    };

    loop.call_later(20, say("timer of 20"));
    loop.call_later(10, say("timer of 10"));
    loop.call_soon([&] {
        say("first callback")();
        loop.call_soon(say("callback that the first callback added"));
    });
    loop.call_soon(say("second callback"));
    loop.run();

    std::cout << "order of the callbacks:\n";
    for (const auto& line : log) std::cout << "  " << line << "\n";
    std::cout << "turns of the loop: " << loop.turns() << "\n";
}
Output
order of the callbacks:
  time 0: first callback
  time 0: second callback
  time 0: callback that the first callback added
  time 10: timer of 10
  time 20: timer of 20
turns of the loop: 4
  • Verdict: idiom. A small loop class with a std::deque of std::function callbacks and a std::priority_queue of timers.
JavaGitHub
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

public class Main {
    record Timer(int due, int order, Runnable callback) {}

    // One thread takes ready callbacks from a queue and runs each one to the end.
    static class EventLoop {
        final ArrayDeque<Runnable> ready = new ArrayDeque<>(); // callbacks to run in this turn or the next
        final PriorityQueue<Timer> timers =
                new PriorityQueue<>(Comparator.comparingInt(Timer::due).thenComparingInt(Timer::order));
        int now = 0; // a counter clock, so the output does not depend on the machine
        int order = 0;
        int turns = 0;

        void callSoon(Runnable callback) {
            ready.addLast(callback);
        }

        void callLater(int delay, Runnable callback) {
            timers.add(new Timer(now + delay, ++order, callback));
        }

        void run() {
            while (!ready.isEmpty() || !timers.isEmpty()) {
                if (ready.isEmpty()) now = timers.peek().due(); // a real loop sleeps or waits for I/O here
                while (!timers.isEmpty() && timers.peek().due() <= now) ready.addLast(timers.poll().callback());
                turns++;
                int count = ready.size(); // callbacks added now wait for the next turn
                for (int i = 0; i < count; i++) ready.pollFirst().run();
            }
        }
    }

    static final EventLoop loop = new EventLoop();
    static final List<String> log = new ArrayList<>();

    static Runnable say(String text) {
        return () -> log.add("time " + loop.now + ": " + text);
    }

    public static void main(String[] args) {
        loop.callLater(20, say("timer of 20"));
        loop.callLater(10, say("timer of 10"));
        loop.callSoon(() -> {
            say("first callback").run();
            loop.callSoon(say("callback that the first callback added"));
        });
        loop.callSoon(say("second callback"));
        loop.run();

        System.out.println("order of the callbacks:");
        for (String line : log) System.out.println("  " + line);
        System.out.println("turns of the loop: " + loop.turns);
    }
}
Output
order of the callbacks:
  time 0: first callback
  time 0: second callback
  time 0: callback that the first callback added
  time 10: timer of 10
  time 20: timer of 20
turns of the loop: 4
  • Verdict: idiom. A small loop class with an ArrayDeque of Runnable callbacks and a PriorityQueue of timer records.
using System;
using System.Collections.Generic;

// One thread takes ready callbacks from a queue and runs each one to the end.
class EventLoop
{
    readonly Queue<Action> ready = new Queue<Action>(); // callbacks to run in this turn or the next
    readonly PriorityQueue<Action, (int Due, int Order)> timers = new PriorityQueue<Action, (int, int)>();
    public int Now; // a counter clock, so the output does not depend on the machine
    int order;
    public int Turns;

    public void CallSoon(Action callback) => ready.Enqueue(callback);

    public void CallLater(int delay, Action callback) => timers.Enqueue(callback, (Now + delay, ++order));

    public void Run()
    {
        while (ready.Count > 0 || timers.Count > 0)
        {
            if (ready.Count == 0 && timers.TryPeek(out _, out var first)) Now = first.Due; // a real loop sleeps or waits for I/O here
            while (timers.TryPeek(out _, out var next) && next.Due <= Now) ready.Enqueue(timers.Dequeue());
            Turns++;
            int count = ready.Count; // callbacks added now wait for the next turn
            for (int i = 0; i < count; i++) ready.Dequeue()();
        }
    }
}

class Program
{
    static readonly EventLoop loop = new EventLoop();
    static readonly List<string> log = new List<string>();

    static Action Say(string text) => () => log.Add($"time {loop.Now}: {text}");

    static void Main()
    {
        loop.CallLater(20, Say("timer of 20"));
        loop.CallLater(10, Say("timer of 10"));
        loop.CallSoon(() =>
        {
            Say("first callback")();
            loop.CallSoon(Say("callback that the first callback added"));
        });
        loop.CallSoon(Say("second callback"));
        loop.Run();

        Console.WriteLine("order of the callbacks:");
        foreach (var line in log) Console.WriteLine("  " + line);
        Console.WriteLine("turns of the loop: " + loop.Turns);
    }
}
Output
order of the callbacks:
  time 0: first callback
  time 0: second callback
  time 0: callback that the first callback added
  time 10: timer of 10
  time 20: timer of 20
turns of the loop: 4
  • Verdict: idiom. A small loop class with a Queue<Action> and a PriorityQueue of timers that has a tuple priority.
JavaScriptGitHub
// One thread takes ready callbacks from a queue and runs each one to the end.
// JavaScript already runs on an event loop; this small one shows its parts.
class EventLoop {
  constructor() {
    this.ready = []; // callbacks to run in this turn or the next
    this.timers = []; // [due time, order, callback], kept sorted
    this.now = 0; // a counter clock, so the output does not depend on the machine
    this.order = 0;
    this.turns = 0;
  }

  callSoon(callback) {
    this.ready.push(callback);
  }

  callLater(delay, callback) {
    this.order++;
    this.timers.push([this.now + delay, this.order, callback]);
    this.timers.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
  }

  run() {
    while (this.ready.length > 0 || this.timers.length > 0) {
      if (this.ready.length === 0) this.now = this.timers[0][0]; // a real loop sleeps or waits for I/O here
      while (this.timers.length > 0 && this.timers[0][0] <= this.now) {
        this.ready.push(this.timers.shift()[2]);
      }
      this.turns++;
      const count = this.ready.length; // callbacks added now wait for the next turn
      for (let i = 0; i < count; i++) this.ready.shift()();
    }
  }
}

const loop = new EventLoop();
const log = [];

function say(text) {
  return () => log.push(`time ${loop.now}: ${text}`);
}

function first() {
  say("first callback")();
  loop.callSoon(say("callback that the first callback added"));
}

loop.callLater(20, say("timer of 20"));
loop.callLater(10, say("timer of 10"));
loop.callSoon(first);
loop.callSoon(say("second callback"));
loop.run();

console.log("order of the callbacks:");
for (const line of log) console.log("  " + line);
console.log("turns of the loop: " + loop.turns);
Output
order of the callbacks:
  time 0: first callback
  time 0: second callback
  time 0: callback that the first callback added
  time 10: timer of 10
  time 20: timer of 20
turns of the loop: 4
  • Verdict: idiom. JavaScript already runs on an event loop. The example builds a small one with an array of callbacks and a sorted array of timers to show the parts.
TypeScriptGitHub
// One thread takes ready callbacks from a queue and runs each one to the end.
// JavaScript already runs on an event loop; this small one shows its parts.
type Callback = () => void;

class EventLoop {
  ready: Callback[] = []; // callbacks to run in this turn or the next
  timers: [number, number, Callback][] = []; // [due time, order, callback], kept sorted
  now = 0; // a counter clock, so the output does not depend on the machine
  order = 0;
  turns = 0;

  callSoon(callback: Callback): void {
    this.ready.push(callback);
  }

  callLater(delay: number, callback: Callback): void {
    this.order++;
    this.timers.push([this.now + delay, this.order, callback]);
    this.timers.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
  }

  run(): void {
    while (this.ready.length > 0 || this.timers.length > 0) {
      if (this.ready.length === 0) this.now = this.timers[0][0]; // a real loop sleeps or waits for I/O here
      while (this.timers.length > 0 && this.timers[0][0] <= this.now) {
        this.ready.push(this.timers.shift()![2]);
      }
      this.turns++;
      const count = this.ready.length; // callbacks added now wait for the next turn
      for (let i = 0; i < count; i++) this.ready.shift()!();
    }
  }
}

const loop = new EventLoop();
const log: string[] = [];

function say(text: string): Callback {
  return () => {
    log.push(`time ${loop.now}: ${text}`);
  };
}

function first(): void {
  say("first callback")();
  loop.callSoon(say("callback that the first callback added"));
}

loop.callLater(20, say("timer of 20"));
loop.callLater(10, say("timer of 10"));
loop.callSoon(first);
loop.callSoon(say("second callback"));
loop.run();

console.log("order of the callbacks:");
for (const line of log) console.log("  " + line);
console.log("turns of the loop: " + loop.turns);
Output
order of the callbacks:
  time 0: first callback
  time 0: second callback
  time 0: callback that the first callback added
  time 10: timer of 10
  time 20: timer of 20
turns of the loop: 4
  • Verdict: idiom. The same small loop with typed callbacks and timers. TypeScript code runs on the event loop of its host.
package main

import (
	"container/heap"
	"fmt"
)

type timer struct {
	due, order int
	callback   func()
}

// timerHeap keeps the timers in order of due time, then of order.
type timerHeap []timer

func (h timerHeap) Len() int { return len(h) }
func (h timerHeap) Less(i, j int) bool {
	return h[i].due < h[j].due || (h[i].due == h[j].due && h[i].order < h[j].order)
}
func (h timerHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *timerHeap) Push(x any)   { *h = append(*h, x.(timer)) }
func (h *timerHeap) Pop() any {
	old := *h
	t := old[len(old)-1]
	*h = old[:len(old)-1]
	return t
}

// EventLoop takes ready callbacks from a queue on one goroutine and runs each one to the end.
type EventLoop struct {
	ready  []func() // callbacks to run in this turn or the next
	timers timerHeap
	now    int // a counter clock, so the output does not depend on the machine
	order  int
	turns  int
}

func (l *EventLoop) CallSoon(callback func()) { l.ready = append(l.ready, callback) }

func (l *EventLoop) CallLater(delay int, callback func()) {
	l.order++
	heap.Push(&l.timers, timer{l.now + delay, l.order, callback})
}

func (l *EventLoop) Run() {
	for len(l.ready) > 0 || len(l.timers) > 0 {
		if len(l.ready) == 0 {
			l.now = l.timers[0].due // a real loop sleeps or waits for I/O here
		}
		for len(l.timers) > 0 && l.timers[0].due <= l.now {
			l.ready = append(l.ready, heap.Pop(&l.timers).(timer).callback)
		}
		l.turns++
		batch := l.ready // callbacks added now wait for the next turn
		l.ready = nil
		for _, callback := range batch {
			callback()
		}
	}
}

func main() {
	loop := &EventLoop{}
	var log []string
	say := func(text string) func() {
		return func() { log = append(log, fmt.Sprintf("time %d: %s", loop.now, text)) }
	}

	loop.CallLater(20, say("timer of 20"))
	loop.CallLater(10, say("timer of 10"))
	loop.CallSoon(func() {
		say("first callback")()
		loop.CallSoon(say("callback that the first callback added"))
	})
	loop.CallSoon(say("second callback"))
	loop.Run()

	fmt.Println("order of the callbacks:")
	for _, line := range log {
		fmt.Println(" ", line)
	}
	fmt.Println("turns of the loop:", loop.turns)
}
Output
order of the callbacks:
  time 0: first callback
  time 0: second callback
  time 0: callback that the first callback added
  time 10: timer of 10
  time 20: timer of 20
turns of the loop: 4
  • Verdict: idiom. A small loop type with a slice of callbacks and a container/heap of timers. All callbacks run on the goroutine that calls Run.
RustGitHub
use std::cell::{Cell, RefCell};
use std::cmp::Reverse;
use std::collections::{BinaryHeap, HashMap, VecDeque};
use std::rc::Rc;

type Callback = Box<dyn FnOnce()>;

// One thread takes ready callbacks from a queue and runs each one to the end.
#[derive(Default)]
struct EventLoop {
    ready: RefCell<VecDeque<Callback>>, // callbacks to run in this turn or the next
    timers: RefCell<BinaryHeap<Reverse<(u32, u32)>>>, // (due time, order)
    timer_callbacks: RefCell<HashMap<u32, Callback>>, // order -> callback
    now: Cell<u32>, // a counter clock, so the output does not depend on the machine
    order: Cell<u32>,
    turns: Cell<u32>,
}

impl EventLoop {
    fn call_soon(&self, callback: Callback) {
        self.ready.borrow_mut().push_back(callback);
    }

    fn call_later(&self, delay: u32, callback: Callback) {
        let order = self.order.get() + 1;
        self.order.set(order);
        self.timers.borrow_mut().push(Reverse((self.now.get() + delay, order)));
        self.timer_callbacks.borrow_mut().insert(order, callback);
    }

    fn run(&self) {
        while !self.ready.borrow().is_empty() || !self.timers.borrow().is_empty() {
            if self.ready.borrow().is_empty() {
                let Reverse((due, _)) = *self.timers.borrow().peek().unwrap();
                self.now.set(due); // a real loop sleeps or waits for I/O here
            }
            loop {
                let next = self.timers.borrow().peek().copied();
                match next {
                    Some(Reverse((due, order))) if due <= self.now.get() => {
                        self.timers.borrow_mut().pop();
                        let callback = self.timer_callbacks.borrow_mut().remove(&order).unwrap();
                        self.ready.borrow_mut().push_back(callback);
                    }
                    _ => break,
                }
            }
            self.turns.set(self.turns.get() + 1);
            let count = self.ready.borrow().len(); // callbacks added now wait for the next turn
            for _ in 0..count {
                let callback = self.ready.borrow_mut().pop_front().unwrap();
                callback(); // no borrow is held here, so the callback can add callbacks
            }
        }
    }
}

fn main() {
    let event_loop = Rc::new(EventLoop::default());
    let log = Rc::new(RefCell::new(Vec::<String>::new()));
    let say = {
        let (event_loop, log) = (Rc::clone(&event_loop), Rc::clone(&log));
        move |text: &str| -> Callback {
            let (event_loop, log, text) = (Rc::clone(&event_loop), Rc::clone(&log), text.to_string());
            Box::new(move || log.borrow_mut().push(format!("time {}: {}", event_loop.now.get(), text)))
        }
    };

    event_loop.call_later(20, say("timer of 20"));
    event_loop.call_later(10, say("timer of 10"));
    let first = {
        let (event_loop, say) = (Rc::clone(&event_loop), say.clone());
        move || {
            say("first callback")();
            event_loop.call_soon(say("callback that the first callback added"));
        }
    };
    event_loop.call_soon(Box::new(first));
    event_loop.call_soon(say("second callback"));
    event_loop.run();

    println!("order of the callbacks:");
    for line in log.borrow().iter() {
        println!("  {}", line);
    }
    println!("turns of the loop: {}", event_loop.turns.get());
}
Output
order of the callbacks:
  time 0: first callback
  time 0: second callback
  time 0: callback that the first callback added
  time 10: timer of 10
  time 20: timer of 20
turns of the loop: 4
  • Verdict: idiom. A small loop with RefCell and Cell fields shared through Rc, so a callback can add callbacks; no borrow is held while a callback runs.

Consequences

Benefits:

  • One thread handles many events, and the callbacks do not need locks, because a callback cannot be stopped in the middle to run another callback.2
  • The order is easy to follow. In the example, the callbacks run in the order they were added, and the timers run in the order of their due times.
  • The program stays responsive while it waits. When the application is waiting for a query or a fetch() request to return, it can still process other things like user input.2

Liabilities:

  • A slow callback stops the whole program. If a job takes too long to complete, the web application is unable to process user interactions like click or scroll.2
  • The loop uses one processor. Work that needs a lot of processing must go to other threads or processes.
  • Other threads must not touch the loop directly. In asyncio, call_soon() is not thread-safe, and another thread must use loop.call_soon_threadsafe() to schedule a callback.4
  • Code that waits must be split into callbacks, or written with async and await, which the loop runs as a series of callbacks.

In this program, a callback calls time.sleep, so the loop cannot run the timer when it is due:

This code runs but gives a wrong answer on purpose.

import asyncio
import time


def blocking_work():
    time.sleep(0.3)  # wrong: this blocks the one thread that runs the loop


async def main():
    loop = asyncio.get_running_loop()
    start = time.monotonic()
    ran_at = []
    loop.call_later(0.05, lambda: ran_at.append(time.monotonic() - start))
    loop.call_soon(blocking_work)
    await asyncio.sleep(0.4)
    print("timer due after 0.05 s")
    print("timer ran only after the blocking work, at 0.3 s or later:", ran_at[0] >= 0.3)


asyncio.run(main())
Output
timer due after 0.05 s
timer ran only after the blocking work, at 0.3 s or later: True

When not to use it

Do not use an event loop for work that is mostly computation. One thread does not use the other processors, and long callbacks make the loop late for every other event. A thread pool or fork-join fits that work. Do not use an event loop when the program must call libraries that block and cannot be changed, unless the loop can send those calls to other threads.

  • Blocking work on a thread pool. asyncio's loop.run_in_executor() arranges for a function to be called in an executor,4 which is a thread pool by default. The loop keeps running while the function runs:
import asyncio
import time


def blocking_work():
    time.sleep(0.3)  # runs on a worker thread, not on the loop thread


async def main():
    loop = asyncio.get_running_loop()
    start = time.monotonic()
    ran_at = []
    loop.call_later(0.05, lambda: ran_at.append(time.monotonic() - start))
    await loop.run_in_executor(None, blocking_work)  # the loop keeps running meanwhile
    print("timer due after 0.05 s")
    print("timer ran before the blocking work ended:", ran_at[0] < 0.3)


asyncio.run(main())
Output
timer due after 0.05 s
timer ran before the blocking work ended: True
  • Phases. The Node.js event loop has phases, such as timers, poll and check, and each phase has a FIFO queue of callbacks to execute.3
  • Tasks and microtasks. HTML event loops split jobs into two categories, and the microtask queue is drained first before the task queue is pulled.2
  • Reactor is the event loop for I/O: it waits on many handles and dispatches the handler of each handle that is ready. Proactor dispatches the handler when an asynchronous operation completes.
  • Half-sync/half-async joins an event loop for I/O with threads for the slow work, as the run block does.
  • Thread confinement is the reason that the loop needs no locks: only the loop thread touches the data of the callbacks.

Known uses

  • Web browsers: a web page and its JavaScript typically run in a single-threaded web browser process, which deals with messages from a queue one at a time.1
  • Node.js runs JavaScript callbacks on its event loop.3
  • Python: the event loop is the core of every asyncio application, and runs asynchronous tasks and callbacks, network I/O operations and subprocesses.4
  • Windows: a process that interacts with the user must accept and react to incoming messages, which is almost inevitably done by a message loop in that process.1
  • X Window System: applications that use Xlib directly are built around the XNextEvent family of functions.1
  • GLib: the GLib event loop was originally created for use in GTK, but it is now used in non-GUI applications as well, such as D-Bus.1

References

  1. Event loop, Wikipedia, lead; Examples
  2. JavaScript execution model, MDN Web Docs, Job queue and event loop; Run-to-completion; Never blocking
  3. The Node.js Event Loop, Node.js documentation, What is the Event Loop?; Event Loop Explained; Phases Overview
  4. Event loop, asyncio, Python documentation, Preface; loop.call_soon; loop.call_later; loop.call_soon_threadsafe; loop.run_in_executor

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source