Skip to main content

StaticDeferred

Struct StaticDeferred 

Source
pub struct StaticDeferred<T> { /* private fields */ }
Available on crate feature static-deferred only.
Expand description

A task’s result, kept in a static instead of on the heap.

Use it on targets without a heap allocator, or to keep memory use fixed. Each kind of job gets its own static StaticDeferred and its own task, which runs the job through a Ticket. All methods take &self, so the static can be used from anywhere.

Needs a critical-section implementation, which embassy and the HALs provide. With std, add critical-section = { version = "1", features = ["std"] } to your own dependencies.

Panics in the job are not caught. On targets where a panic unwinds instead of halting, such as std, the StaticDeferred then reports State::Cancelled.

Wait on it (join or cancel_and_wait) from one task at a time; waiting twice from the same task, for example with join!, is fine. Waiting from several tasks at once also works, but uses more CPU while they wait, and a join that ends without a result may then report Error::Cancelled instead of Error::NotStarted. A join that returns Ok always has the result of its run.

§Examples

ⓘ
use async_deferred::{StaticDeferred, Ticket};

static SENSOR: StaticDeferred<u16> = StaticDeferred::new();

#[embassy_executor::task]
async fn sensor_task(ticket: Ticket<'static, u16>) {
    ticket.run(read_sensor()).await;
}

#[embassy_executor::main]
async fn main(spawner: embassy_executor::Spawner) {
    spawner.spawn(sensor_task(SENSOR.begin().unwrap()).unwrap());

    // ... do other work ...

    if let Some(value) = SENSOR.take() {
        // use the reading
    }
}

Implementations§

Source§

impl<T> StaticDeferred<T>

Source

pub const fn new() -> Self

Creates a StaticDeferred with no task, for use in a static.

Source

pub fn begin(&self) -> Result<Ticket<'_, T>, BeginError>

Starts a new run and returns its Ticket. Pass the ticket to the task that runs the job, and call Ticket::run there.

Returns BeginError::AlreadyStarted if a run is in progress or its result has not been taken. If the ticket is dropped without running, for example because the task could not be spawned, the StaticDeferred goes back to State::NotStarted.

Source

pub fn state(&self) -> State

Returns the current State without waiting.

Never reports a panic: panics in the job are not caught.

Source

pub fn is_not_started(&self) -> bool

Returns true if no run has been started, or its result was taken.

Source

pub fn is_pending(&self) -> bool

Returns true if a run is in progress.

Source

pub fn is_ready(&self) -> bool

Returns true if the result is available.

Source

pub fn is_cancelled(&self) -> bool

Returns true if the task was dropped before it finished.

Source

pub fn take(&self) -> Option<T>

Moves the result out if the run has finished, without waiting.

On success, a new run can be started.

Source

pub fn with_result<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R>

Calls f with the result if the run has finished, without moving it out.

Keep f short: on most embedded targets, interrupts are blocked while it runs. Don’t use the same StaticDeferred inside f; that panics.

Source

pub async fn join(&self) -> Result<T, Error>

Waits for the run to finish and moves its result out.

Returns Error::NotStarted if no run is in progress and no result is waiting, or if another task took the result first. Returns Error::Cancelled if the run was cancelled or its task was dropped before it finished. A join only waits for the run that was in progress when it started, never for a later one. A Ticket dropped without running counts as a dropped task.

With several tasks waiting at once, the error kind may be Cancelled where NotStarted would be accurate; see the type’s docs.

Source

pub fn cancel(&self) -> bool

Stops the run in progress and resets to State::NotStarted, so a new run can begin.

The task may still be using its executor resources, such as an embassy task pool slot, when this returns. To start a new run right away in a full task pool, use cancel_and_wait instead. Returns false and does nothing if no run is in progress.

Source

pub async fn cancel_and_wait(&self) -> bool

Like cancel, and waits until no task of this StaticDeferred is still running, including tasks cancelled earlier.

On a single-threaded executor such as embassy, their task pool slots are free when this returns. It waits for every ticket from begin to be run or dropped, so don’t start a new run from elsewhere while waiting. A ticket that is neither run nor dropped, for example passed to mem::forget, makes this wait forever. Returns true if a run was in progress.

ⓘ
// The sensor hung: stop it, then start again once its task is gone.
SENSOR.cancel_and_wait().await;
if let Ok(ticket) = SENSOR.begin() {
    if let Ok(token) = sensor_task(ticket) {
        spawner.spawn(token);
    }
}

Trait Implementations§

Source§

impl<T> Debug for StaticDeferred<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Default for StaticDeferred<T>

Source§

fn default() -> Self

Auto Trait Implementations§

§

impl<T> !Freeze for StaticDeferred<T>

§

impl<T> !RefUnwindSafe for StaticDeferred<T>

§

impl<T> Forget for StaticDeferred<T>

§

impl<T> Move for StaticDeferred<T>

§

impl<T> Send for StaticDeferred<T>
where Mutex<RefCell<Shared<T>>>: Send,

§

impl<T> Sync for StaticDeferred<T>
where Mutex<RefCell<Shared<T>>>: Sync,

§

impl<T> Unpin for StaticDeferred<T>
where Mutex<RefCell<Shared<T>>>: Unpin,

§

impl<T> UnsafeUnpin for StaticDeferred<T>
where Mutex<RefCell<Shared<T>>>: UnsafeUnpin,

§

impl<T> UnwindSafe for StaticDeferred<T>
where Mutex<RefCell<Shared<T>>>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.