Skip to main content

task/
lib.rs

1#![no_std]
2
3extern crate alloc;
4
5embedded_i18n::i18n!("locales");
6
7#[cfg(any(
8    test,
9    feature = "std",
10    target_os = "linux",
11    target_os = "macos",
12    target_os = "windows",
13    target_arch = "wasm32"
14))]
15extern crate std;
16
17#[cfg(all(feature = "profiling", target_os = "linux"))]
18pub mod profiling;
19
20#[cfg(any(test, feature = "test_harness"))]
21pub mod test_executor;
22
23#[cfg(feature = "crash")]
24pub mod active_task;
25
26pub mod metrics;
27
28mod environment_variable;
29mod error;
30mod join_handle;
31#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
32mod macrotask;
33mod manager;
34mod signal;
35mod task;
36#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
37mod time_driver;
38
39use core::{future::poll_fn, task::Poll, time::Duration};
40use embassy_time::{Instant, Timer};
41
42pub use embassy_executor;
43pub use environment_variable::*;
44pub use error::*;
45pub use join_handle::*;
46pub use manager::*;
47pub use signal::*;
48pub use task::*;
49pub use task_macros::{run, test};
50
51/// The Embassy instant at which a wait of `nanoseconds` has fully elapsed.
52///
53/// `embassy_time::Duration::from_nanos` adds 999 before dividing, which wraps for
54/// huge values (a debug build panics and a release build returns at once), and
55/// `Timer::after` starts from the current tick rounded down, so a wait could end
56/// up to a tick early. This rounds the ticks up, adds one tick to every non-zero
57/// wait and saturates, so `u64::MAX` waits practically forever.
58pub fn deadline_after_nanoseconds(nanoseconds: u64) -> Instant {
59    const fn gcd(a: u64, b: u64) -> u64 {
60        if b == 0 { a } else { gcd(b, a % b) }
61    }
62    const DIVISOR: u64 = gcd(embassy_time::TICK_HZ, 1_000_000_000);
63    const TICKS: u64 = embassy_time::TICK_HZ / DIVISOR;
64    const NANOSECONDS: u64 = 1_000_000_000 / DIVISOR;
65    // The remainder is below `NANOSECONDS`, so its product with `TICKS` must fit.
66    const _: () = assert!(NANOSECONDS.checked_mul(TICKS).is_some());
67
68    let ticks = if nanoseconds == 0 {
69        0
70    } else {
71        let whole = (nanoseconds / NANOSECONDS).saturating_mul(TICKS);
72        let part = (nanoseconds % NANOSECONDS * TICKS).div_ceil(NANOSECONDS);
73        whole.saturating_add(part).saturating_add(1)
74    };
75    Instant::from_ticks(Instant::now().as_ticks().saturating_add(ticks))
76}
77
78/// Sleep the current thread for a given duration.
79pub async fn sleep(duration: impl Into<Duration>) {
80    let nanoseconds = u64::try_from(duration.into().as_nanos()).unwrap_or(u64::MAX);
81
82    Timer::at(deadline_after_nanoseconds(nanoseconds)).await
83}
84
85/// How long [`yield_throttled`] sleeps on WebAssembly targets.
86#[cfg(target_arch = "wasm32")]
87const THROTTLED_YIELD: Duration = Duration::from_millis(10);
88
89/// Yield the current thread, allowing other tasks to run.
90///
91/// The task is rescheduled as soon as the other ready tasks have run. Use this
92/// to slice long computations into quanta. A task that polls for an event
93/// should call [`yield_throttled`] instead, so that it does not keep a
94/// single-threaded host busy.
95///
96/// On `wasm32-unknown-unknown` this ends the current browser task: timers,
97/// input and rendering that are already due run before the task resumes, and it
98/// costs far less than a millisecond. Embassy's own wasm yield is a microtask
99/// that would starve all of them, and a timer-backed yield costs 10 ms or more
100/// per call, which throttles anything that yields often (the Wasm runtime
101/// yields once per fuel quantum, so a timer made audio rendering choppy).
102/// Where the browser exposes no `MessageChannel`, it falls back to a zero-delay
103/// timer, and where there is no timer either (an `AudioWorkletGlobalScope`) to
104/// a microtask. The microtask fallback does not let the host run: a loop that
105/// only yields starves everything else in its scope, so such a scope must wait
106/// on something other than `yield_now` (and cannot use [`sleep`], which needs a
107/// timer). On `wasm32-wasip1` it sleeps 10 ms: there is no host event loop to
108/// give control to.
109pub async fn yield_now() {
110    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
111    macrotask::yield_now().await;
112
113    // Embassy's wasm pender uses `Promise.then` (a microtask), so a self-waking
114    // yield cannot let the host run. Keep a timer-backed yield.
115    #[cfg(all(target_arch = "wasm32", not(target_os = "unknown")))]
116    sleep(THROTTLED_YIELD).await;
117
118    #[cfg(not(target_arch = "wasm32"))]
119    embassy_futures::yield_now().await;
120}
121
122/// Yield the current thread, but never resume faster than a polling loop should.
123///
124/// For guest-initiated busy-waits (`sched_yield`, a zero-delay poll) whose
125/// caller makes no progress until something else changes: such a loop must not
126/// peg a single-threaded host at 100 %. On WebAssembly targets this sleeps
127/// 10 ms (the timer-backed yield [`yield_now`] used to be); elsewhere it is
128/// [`yield_now`], since the scheduler there already runs other tasks and idles
129/// when none is ready.
130///
131/// Do not use it to slice work that is making progress, because the wait is
132/// not cheap: use [`yield_now`].
133pub async fn yield_throttled() {
134    #[cfg(target_arch = "wasm32")]
135    sleep(THROTTLED_YIELD).await;
136
137    #[cfg(not(target_arch = "wasm32"))]
138    yield_now().await;
139}
140
141/// Suspend the current task until the provided function is called with a context.
142/// The function will be called with a mutable reference to the task's context, allowing it to wake the
143pub async fn suspend(function: impl FnOnce(&mut core::task::Context<'_>)) {
144    let mut function_opt = Some(function);
145
146    poll_fn(|context| {
147        if let Some(f) = function_opt.take() {
148            f(context);
149            Poll::Pending
150        } else {
151            Poll::Ready(())
152        }
153    })
154    .await;
155}
156
157pub fn block_on<F: core::future::Future>(future: F) -> F::Output {
158    embassy_futures::block_on(future)
159}
160
161#[cfg(test)]
162mod tests {
163    use super::{Instant, deadline_after_nanoseconds};
164
165    #[test]
166    fn deadline_rounds_up_and_saturates() {
167        let now = Instant::now().as_ticks();
168        assert!(deadline_after_nanoseconds(0).as_ticks() >= now);
169        // Every non-zero wait ends after the tick it started in.
170        assert!(deadline_after_nanoseconds(1).as_ticks() > now);
171        // A wait of one second needs at least `TICK_HZ` ticks.
172        assert!(
173            deadline_after_nanoseconds(1_000_000_000).as_ticks() >= now + embassy_time::TICK_HZ
174        );
175        // The largest requests neither wrap nor panic.
176        let far = deadline_after_nanoseconds(u64::MAX).as_ticks();
177        assert!(far > deadline_after_nanoseconds(u64::MAX / 2).as_ticks());
178        assert!(far > now + embassy_time::TICK_HZ);
179    }
180}