embedded_executor/
sleep.rs

1//! Abstraction over platform-specific thread sleeping mechanisms.
2
3/// Platform-agnostic Sleep trait
4///
5/// Provides a mechanism that can be used to sleep the
6/// current thread.
7pub trait Sleep {
8    /// Put the current thread to sleep.
9    fn sleep(&self);
10}
11
12#[cfg(any(feature = "alloc", feature = "std"))]
13mod provided {
14    use super::*;
15
16    use alloc::sync::Arc;
17
18    use core::sync::atomic::{
19        self,
20        AtomicBool,
21        Ordering::*,
22    };
23
24    use crate::Wake;
25
26    /// Simple atomic spinlock sleep implementation.
27    #[derive(Default, Clone, Debug)]
28    pub struct SpinSleep(Arc<AtomicBool>);
29
30    impl Sleep for SpinSleep {
31        fn sleep(&self) {
32            loop {
33                if self.0.swap(false, Acquire) {
34                    break;
35                } else {
36                    atomic::spin_loop_hint();
37                }
38            }
39        }
40    }
41
42    impl Wake for SpinSleep {
43        fn wake(&self) {
44            self.0.store(true, Release)
45        }
46    }
47}
48
49#[cfg(any(feature = "std", feature = "alloc"))]
50pub use self::provided::*;