Skip to main content

task/
test_executor.rs

1//! Single-threaded std executor for tests (`test_harness` feature).
2//!
3//! Lets `#[task::test]` and test helpers run without any platform crate.
4//! Embassy's `platform-std` provides the pender that wakes [`Executor`].
5
6extern crate std;
7
8use alloc::boxed::Box;
9use core::marker::PhantomData;
10use embassy_executor::{Spawner, raw};
11use portable_atomic::{AtomicBool, Ordering};
12use std::sync::{Condvar, Mutex};
13use synchronization::blocking_mutex::raw::CriticalSectionRawMutex;
14use synchronization::signal::Signal;
15
16use crate::{Manager, SpawnerIdentifier, metrics::ExecutorActivity};
17
18/// A std executor that [`Executor::run`] until [`Executor::stop`] is called.
19pub struct Executor {
20    inner: raw::Executor,
21    not_send: PhantomData<*mut ()>,
22    signaler: &'static Signaler,
23    stop: AtomicBool,
24}
25
26impl Default for Executor {
27    fn default() -> Self {
28        Self::new()
29    }
30}
31
32impl Executor {
33    pub fn new() -> Self {
34        let signaler = Box::leak(Box::new(Signaler::new()));
35        Self {
36            inner: raw::Executor::new(signaler as *mut Signaler as *mut ()),
37            not_send: PhantomData,
38            signaler,
39            stop: AtomicBool::new(false),
40        }
41    }
42
43    pub fn stop(&self) {
44        self.stop.store(true, Ordering::SeqCst);
45        self.signaler.signal();
46    }
47
48    pub fn spawner(&'static self) -> Spawner {
49        self.inner.spawner()
50    }
51
52    /// Call `init` with a spawner, then poll tasks until [`Self::stop`].
53    pub fn run(&'static self, init: impl FnOnce(Spawner, &'static Self)) {
54        // Create the hook before registering, so every snapshot that sees
55        // this executor already reports its idle time.
56        let activity = self.activity();
57        init(self.inner.spawner(), self);
58        while !self.stop.load(Ordering::SeqCst) {
59            self.poll_and_wait(&activity);
60        }
61    }
62
63    /// Call `init` with a spawner, then poll tasks forever.
64    pub fn start(&'static self, init: impl FnOnce(Spawner)) -> ! {
65        let activity = self.activity();
66        init(self.inner.spawner());
67        loop {
68            self.poll_and_wait(&activity);
69        }
70    }
71
72    /// Idle accounting hook, as platform executors should use it.
73    fn activity(&'static self) -> ExecutorActivity {
74        ExecutorActivity::new(self.inner.spawner())
75    }
76
77    fn poll_and_wait(&'static self, activity: &ExecutorActivity) {
78        unsafe { self.inner.poll() };
79        activity.measure_idle(|| self.signaler.wait());
80    }
81}
82
83// Layout shared with embassy's `platform-std` pender.
84struct Signaler {
85    mutex: Mutex<bool>,
86    condvar: Condvar,
87}
88
89impl Signaler {
90    fn new() -> Self {
91        Self {
92            mutex: Mutex::new(false),
93            condvar: Condvar::new(),
94        }
95    }
96
97    fn wait(&self) {
98        let mut signaled = self.mutex.lock().unwrap();
99        while !*signaled {
100            signaled = self.condvar.wait(signaled).unwrap();
101        }
102        *signaled = false;
103    }
104
105    fn signal(&self) {
106        let mut signaled = self.mutex.lock().unwrap();
107        *signaled = true;
108        self.condvar.notify_one();
109    }
110}
111
112/// A per-call-site static [`Executor`], as used by `#[task::test]`.
113#[macro_export]
114macro_rules! instantiate_test_executor {
115    () => {{
116        static mut __EXECUTOR: Option<$crate::test_executor::Executor> = None;
117        // Callers such as `#[task::test]` may already be in an unsafe block.
118        #[allow(static_mut_refs, unused_unsafe)]
119        unsafe {
120            if __EXECUTOR.is_none() {
121                __EXECUTOR = Some($crate::test_executor::Executor::new());
122            }
123            __EXECUTOR.as_mut().expect("executor is initialized")
124        }
125    }};
126}
127
128/// Start an executor on a new thread and register it with `manager`.
129pub async fn new_thread_executor(manager: &'static Manager) -> SpawnerIdentifier {
130    let signal: &'static Signal<CriticalSectionRawMutex, SpawnerIdentifier> =
131        Box::leak(Box::new(Signal::new()));
132    std::thread::spawn(move || {
133        let executor: &'static Executor = Box::leak(Box::new(Executor::new()));
134        executor.start(move |spawner| {
135            signal.signal(manager.register_spawner(spawner).unwrap());
136        });
137    });
138    signal.wait().await
139}