Skip to main content

ragrig_gpui/
cancel.rs

1//! Cooperative cancellation shared by UI and worker threads.
2
3use std::sync::{
4    Arc,
5    atomic::{AtomicBool, Ordering},
6};
7
8/// A cloneable, thread-safe cancellation flag.
9///
10/// The UI calls [`cancel`](Self::cancel) while a worker checks
11/// [`is_cancelled`](Self::is_cancelled) at its own checkpoints. A finished run
12/// can be followed by another one on the same handle after
13/// [`reset`](Self::reset).
14#[derive(Clone, Debug, Default)]
15pub struct CancelFlag(Arc<AtomicBool>);
16
17impl CancelFlag {
18    /// Creates a fresh, uncancelled flag.
19    pub fn new() -> Self {
20        Self::default()
21    }
22
23    /// Requests cancellation. Every clone observes the request.
24    pub fn cancel(&self) {
25        self.0.store(true, Ordering::Release);
26    }
27
28    /// Returns whether cancellation has been requested.
29    pub fn is_cancelled(&self) -> bool {
30        self.0.load(Ordering::Acquire)
31    }
32
33    /// Clears the flag so the handle can start another run.
34    pub fn reset(&self) {
35        self.0.store(false, Ordering::Release);
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn clones_share_one_flag() {
45        let flag = CancelFlag::new();
46        let worker = flag.clone();
47
48        assert!(!worker.is_cancelled());
49        flag.cancel();
50        assert!(worker.is_cancelled());
51
52        flag.reset();
53        assert!(!worker.is_cancelled());
54    }
55}