Skip to main content

photon_ring/
shutdown.rs

1// Copyright 2026 Photon Ring Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! A shared shutdown signal for coordinating graceful termination of
5//! consumer loops.
6
7use alloc::sync::Arc;
8use core::sync::atomic::{AtomicBool, Ordering};
9
10/// A shared shutdown signal for coordinating graceful termination.
11///
12/// ```
13/// use photon_ring::Shutdown;
14///
15/// let shutdown = Shutdown::new();
16/// let flag = shutdown.clone();
17///
18/// // In consumer thread:
19/// // while !flag.is_shutdown() {
20/// //     match sub.try_recv() {
21/// //         Ok(v) => { /* process */ }
22/// //         Err(_) => core::hint::spin_loop(),
23/// //     }
24/// // }
25///
26/// // In main thread:
27/// shutdown.trigger();
28/// assert!(flag.is_shutdown());
29/// ```
30pub struct Shutdown {
31    flag: Arc<AtomicBool>,
32}
33
34impl Shutdown {
35    /// Create a new shutdown signal (not yet triggered).
36    pub fn new() -> Self {
37        Shutdown {
38            flag: Arc::new(AtomicBool::new(false)),
39        }
40    }
41
42    /// Trigger the shutdown signal. All clones will observe `is_shutdown() == true`.
43    pub fn trigger(&self) {
44        self.flag.store(true, Ordering::Release);
45    }
46
47    /// Returns `true` if [`trigger`](Self::trigger) has been called on any clone.
48    pub fn is_shutdown(&self) -> bool {
49        self.flag.load(Ordering::Acquire)
50    }
51}
52
53impl Default for Shutdown {
54    fn default() -> Self {
55        Self::new()
56    }
57}
58
59impl Clone for Shutdown {
60    fn clone(&self) -> Self {
61        Shutdown {
62            flag: self.flag.clone(),
63        }
64    }
65}