FAQ - Help and questions

How do I run slow work on another thread without freezing my desktop window?

#threads#gui#channels#desktoppublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Start the work on a std thread, give the thread the sending end of a channel, and let the UI loop check the receiving end with try_recv on each frame or event. The UI never waits, so it keeps drawing. The result comes back as a message. The pattern is shown with a compiled and run program.

Checked with rustc 1.93.0, Windows 11; the program below was compiled and run (std only, no GUI). The egui variant is in its own thread.

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

#1

Answer#

The UI thread must return to its event loop quickly (see the thread on the event loop). So slow work goes on a second thread, and the two threads talk through a channel:

  1. The UI creates a channel and moves the sender into the new thread.
  2. The thread does the slow work and sends the result.
  3. The UI asks the receiver "is there anything yet?" with try_recv, which never waits, once per frame or per event.
src/main.rsrust
use std::sync::mpsc;
use std::thread;

fn slow_sum(n: u64) -> u64 {
    (1..=n).fold(0u64, |a, b| a.wrapping_add(b * b))
}

fn main() {
    let (tx, rx) = mpsc::channel::<u64>();
    // "Button pressed": start the work on its own thread and return at once.
    let worker = thread::spawn(move || {
        let result = slow_sum(50_000_000);
        let _ = tx.send(result); // ignore the error if the window (receiver) is already gone
    });

    // The UI loop keeps running; each frame it asks "is there a result yet?" without waiting.
    let mut frames = 0u32;
    let result = loop {
        match rx.try_recv() {
            Ok(v) => break v,
            Err(mpsc::TryRecvError::Empty) => frames += 1, // draw a frame, stay responsive
            Err(mpsc::TryRecvError::Disconnected) => panic!("worker died"),
        }
        thread::sleep(std::time::Duration::from_millis(1));
    };
    worker.join().unwrap();
    println!("result = {result}, UI kept running: {}", frames > 0);
}
text
result = 13919798230507451072, UI kept running: true

(The sum uses wrapping arithmetic so it cannot overflow-panic; the number itself is not important.)

In a real program the loop is the toolkit's frame or event handler, and thread::sleep is not needed: the toolkit calls you again by itself. What each toolkit needs to wake up when the result arrives is covered in the egui thread.

Common mistakes#

  • Calling worker.join() in the UI thread to "wait for the result". It blocks exactly like the slow work did.
  • Sending UI objects (widgets, window handles) to the worker. Send plain data and let the UI thread update the widgets; see the thread on Send.
  • Unwrapping tx.send(..) in the worker. If the user closes the window, the receiver is gone and send returns an error; ignoring it lets the thread finish quietly.

Should I use async instead of threads?#

Async is a good fit for many waiting operations (network, timers). For heavy computation a thread is simpler, because async tasks that compute without waiting block their executor thread. Either way the UI receives the result as a message.

How many threads can I start?#

One per task is fine for a few tasks. For many small tasks, use a thread pool crate instead of one thread each.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet