portable_atomic_util::task

Trait Wake

source
pub trait Wake {
    // Required method
    fn wake(this: Arc<Self>);

    // Provided method
    fn wake_by_ref(this: &Arc<Self>) { ... }
}
Expand description

The implementation of waking a task on an executor.

This is an equivalent to [std::task::Wake], but using portable_atomic_util::Arc as a reference-counted pointer. See the documentation for [std::task::Wake] for more details.

Note: Unlike std::task::Wake, all methods take this: instead of self:. This is because using portable_atomic_util::Arc as a receiver requires the unstable arbitrary_self_types feature.

§Examples

A basic block_on function that takes a future and runs it to completion on the current thread.

Note: This example trades correctness for simplicity. In order to prevent deadlocks, production-grade implementations will also need to handle intermediate calls to thread::unpark as well as nested invocations.

use portable_atomic_util::{task::Wake, Arc};
use std::{
    future::Future,
    task::{Context, Poll},
    thread::{self, Thread},
};

/// A waker that wakes up the current thread when called.
struct ThreadWaker(Thread);

impl Wake for ThreadWaker {
    fn wake(this: Arc<Self>) {
        this.0.unpark();
    }
}

/// Run a future to completion on the current thread.
fn block_on<T>(fut: impl Future<Output = T>) -> T {
    // Pin the future so it can be polled.
    let mut fut = Box::pin(fut);

    // Create a new context to be passed to the future.
    let t = thread::current();
    let waker = Arc::new(ThreadWaker(t)).into();
    let mut cx = Context::from_waker(&waker);

    // Run the future to completion.
    loop {
        match fut.as_mut().poll(&mut cx) {
            Poll::Ready(res) => return res,
            Poll::Pending => thread::park(),
        }
    }
}

block_on(async {
    println!("Hi from inside a future!");
});

Required Methods§

source

fn wake(this: Arc<Self>)

Wake this task.

Provided Methods§

source

fn wake_by_ref(this: &Arc<Self>)

Wake this task without consuming the waker.

If an executor supports a cheaper way to wake without consuming the waker, it should override this method. By default, it clones the Arc and calls wake on the clone.

Object Safety§

This trait is not object safe.

Implementors§