FAQ - Help and questions

What is an event loop in a desktop app, and why must I never block it?

#event-loop#gui#desktop#threadspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A desktop app waits for events (clicks, key presses, a resize, a timer, a message from another thread), handles each one quickly and goes back to waiting. While your code handles one event, no other event is processed, so a slow handler freezes the window. Slow work belongs on another thread.

Checked with rustc 1.93.0, Windows 11; the program below was compiled and run (std only, no GUI).

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Every GUI program, whatever the toolkit, has one loop at its core:

  1. Wait until something happens.
  2. Handle that one event.
  3. Go back to 1.

The things that happen are events: a mouse click, a key press, a window resize, "the window needs redrawing", a timer, a request to close. The operating system delivers them to your program; the toolkit turns them into calls to your code (a callback, a match on an enum, or the ui method of egui).

The rule that follows is simple: your handler runs on the same thread as the loop. While it runs, the loop cannot take the next event, so the window cannot redraw, resize smoothly or close. If a handler takes two seconds, the window is frozen for two seconds, and the system may mark the window as "not responding".

The small program below has no window, but its structure is the same: events arrive on a channel, the loop handles them one by one and quickly.

src/main.rsrust
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

enum Event {
    Click,
    Tick,
    Quit,
}

fn main() {
    let (tx, rx) = mpsc::channel();
    // Something outside the loop produces events (here: threads standing in for the OS).
    let t = tx.clone();
    thread::spawn(move || {
        for _ in 0..3 {
            thread::sleep(Duration::from_millis(20));
            t.send(Event::Tick).unwrap();
        }
        t.send(Event::Click).unwrap();
        t.send(Event::Quit).unwrap();
    });
    drop(tx);

    // The event loop: wait for an event, handle it quickly, go back to waiting.
    let mut ticks = 0;
    for event in rx {
        match event {
            Event::Tick => ticks += 1,
            Event::Click => println!("click handled after {ticks} ticks"),
            Event::Quit => break,
        }
    }
    println!("loop ended");
}
text
click handled after 3 ticks
loop ended

Real toolkits add one thing: the part that waits is provided by the operating system, so the loop uses no CPU while nothing happens. See the thread on a background thread for the fix to slow handlers.

Common mistakes#

  • Calling thread::sleep, a blocking network call, a big file read or a long computation in a click handler.
  • Starting a second event loop inside a handler (for example by running a nested dialog loop) without knowing what the toolkit does with it.
  • Spinning in a loop {} that polls for something. Wait on a channel, or let the toolkit wake you.

Does every toolkit have the loop in my code?#

No. In egui and iced you call run_native or iced::run and the library owns the loop; it calls your code. With winit you write the handler that the loop calls; see the winit thread.

Is a callback always on the loop's thread?#

For the toolkits in this category, the code you give to the toolkit (ui, update, view, callbacks) is called on the thread that runs the loop. Check the toolkit's documentation for any exception before using other threads.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet