Answer#
Rust has no safe way to stop another thread from outside. The worker must stop itself, and the usual way is a shared flag: an AtomicBool inside an Arc. The UI sets it; the worker reads it often enough that it reacts quickly and leaves its work in a clean state.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
fn main() {
let cancel = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&cancel);
let worker = thread::spawn(move || {
let mut done = 0u32;
while done < 1000 {
if flag.load(Ordering::Relaxed) {
return (done, true); // stop at a safe point and report it was cancelled
}
thread::sleep(Duration::from_millis(5)); // one unit of work
done += 1;
}
(done, false)
});
thread::sleep(Duration::from_millis(50));
cancel.store(true, Ordering::Relaxed); // the Cancel button
let (done, cancelled) = worker.join().unwrap();
println!("cancelled = {cancelled}, stopped before the end = {}", done < 1000);
}cancelled = true, stopped before the end = trueFor a flag like this, Ordering::Relaxed is enough: only the flag itself is shared, and nothing else relies on it being seen in a particular order with other memory.
Design points:
- Check between units of work. The check cannot interrupt a single long call (a large copy, a blocking read). Split work into chunks small enough that cancel feels immediate.
- Report the outcome. Send a
Cancelledmessage, not silence, so the UI can leave its "working" state. - Clean up. If the worker was writing a file, delete the partial file or write to a temporary name first (see the thread on saving files safely).
Common mistakes#
- Setting the flag and then calling
join()on the UI thread. If the worker is slow to notice, the window freezes. Wait for theCancelledmessage instead. - Reusing one flag for the next task without resetting it. Create a new flag for each task.
Related questions#
What about async tasks?#
They are cancelled by dropping them (or through the runtime's own cancellation tools), which is a different mechanism; read your runtime's documentation.
Sources#
- std::sync::atomic: https://doc.rust-lang.org/std/sync/atomic/ (read 2026-12-05)