Skip to main content

task/
lib.rs

1#![no_std]
2
3extern crate alloc;
4
5#[cfg(any(test, feature = "std"))]
6extern crate std;
7
8mod environment_variable;
9mod error;
10mod join_handle;
11mod manager;
12mod signal;
13mod task;
14
15use core::{future::poll_fn, task::Poll, time::Duration};
16use embassy_time::Timer;
17
18pub use embassy_executor;
19pub use environment_variable::*;
20pub use error::*;
21pub use join_handle::*;
22pub use manager::*;
23pub use signal::*;
24pub use task::*;
25pub use task_macros::{run, test};
26
27/// Sleep the current thread for a given duration.
28pub async fn sleep(duration: impl Into<Duration>) {
29    let nano_seconds = duration.into().as_nanos();
30
31    Timer::after(embassy_time::Duration::from_nanos(nano_seconds as u64)).await
32}
33
34/// Yield the current thread, allowing other tasks to run.
35pub async fn yield_now() {
36    #[cfg(target_arch = "wasm32")]
37    sleep(Duration::from_millis(10)).await; // Weird behavior in wasm, where the task is not properly yielded without a delay
38
39    #[cfg(not(target_arch = "wasm32"))]
40    embassy_futures::yield_now().await;
41}
42
43/// Suspend the current task until the provided function is called with a context.
44/// The function will be called with a mutable reference to the task's context, allowing it to wake the
45pub async fn suspend(function: impl FnOnce(&mut core::task::Context<'_>)) {
46    let mut function_opt = Some(function);
47
48    poll_fn(|context| {
49        if let Some(f) = function_opt.take() {
50            f(context);
51            Poll::Pending
52        } else {
53            Poll::Ready(())
54        }
55    })
56    .await;
57}
58
59pub fn block_on<F: core::future::Future>(future: F) -> F::Output {
60    embassy_futures::block_on(future)
61}