FAQ - Help and questions

Should a GUI app share state with a worker through Arc and Mutex or through channels?

#threads#mutex#channels#guipublished 2 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail
Last post

Short answer

Channels fit events and results, because the UI reads each message once and stays in control of its own state. An Arc around a Mutex fits a value that several threads keep reading and updating, such as a log or a cache. Never hold the lock while doing slow work or drawing.

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

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

2 answers from the Ruststudio team: different approaches, each with its own trade-offs

Sort: Oldest Newest
#2

Approach 1: send messages through a channel#

Use it when the worker produces events or results: progress, a finished download, an error. The UI owns its state and changes it only when it reads a message, so there is one place to look when something is wrong. There is no lock to forget.

See the threads on progress updates and on a background thread for runnable examples.

Trade-off: the UI sees only what the worker chose to send. If the UI wants to inspect a large structure that the worker keeps changing, a channel means copying it again and again.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail
    #3

    Approach 2: share one value with Arc<Mutex<T>>#

    Use it when several threads read and update the same data and a message per change would be clumsy: a log buffer, a cache, a list of items found so far.

    src/main.rsrust
    use std::sync::{Arc, Mutex};
    use std::thread;
    
    #[derive(Default)]
    struct Shared {
        log: Vec<String>,
    }
    
    fn main() {
        let state = Arc::new(Mutex::new(Shared::default()));
        let worker_state = Arc::clone(&state);
        let worker = thread::spawn(move || {
            for i in 0..3 {
                let line = format!("step {i}"); // do the slow part first, with no lock held
                worker_state.lock().unwrap().log.push(line); // lock only for the short update
            }
        });
        worker.join().unwrap();
    
        // The UI thread reads a snapshot each frame.
        let snapshot = state.lock().unwrap().log.clone();
        println!("{snapshot:?}");
    }
    text
    ["step 0", "step 1", "step 2"]

    Rules that keep it safe:

    • Keep the lock short. Do the slow work first, lock, update, unlock (the guard unlocks when it goes out of scope, at the end of the statement here). A UI frame that waits for a worker that holds the lock is a frozen window.
    • Copy out, then draw. Clone the data you need (or the part of it) while holding the lock, release it, then draw from the copy.
    • Handle a poisoned lock. unwrap() on lock() panics if another thread panicked while holding it. Decide whether that is acceptable or recover with into_inner() on the error.
    • Tell the UI to redraw. A change in shared state does not wake a sleeping UI; see the egui repaint thread, or use the toolkit's equivalent.

    Trade-off: easy to read from anywhere, easy to misuse. Prefer approach 1 unless the data really is shared.

    Can the UI hold the lock while it draws?#

    Avoid it. Drawing takes time, and the worker is blocked meanwhile.

    Sources#

      QuoteReply
      Share
      Hacker NewsRedditLinkedInE-mail