Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Async

async, .await & impl Future

In Rust, asynchronous functions are defined by proceeding a synchronous function definition with async keyword which turns the return type into an impl Future<Output = SyncReturnType>, and are executed and consumed by .await-ing it.

An asynchronous function is effectively a state-machine: every .await marks a point where the function yields control back to the async executor.

use trpl::Html;

//                             -> impl Future<Output = Option<String>>
async fn page_title(url: &str) -> Option<String> {
    let resp = trpl::get(url).await;  // awaiting for an async function
    let resp_text = response.text().await;
    Html::parse(&resp_text)
        .select_first("title")
        .map(|title_element| title_element.inner_html())
}

Future Trait

An impl Future<Output = ...> is a value that is not currently available but would be available in the future. Output is the value type. .poll() a future to try to drive it to completion.

  • Poll::Ready(T): Completed with output T.
  • Poll::Pending: Not ready yet, executor should wake and poll again later.
pub trait Future {
    type Output;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}

Pin, Unpin & pin-project

Future::poll() takes Pin<&mut Self> because async state machines may contain self-references across suspension points.

  • Pin<T> guarantees the pointee will not move in memory.
  • Most types are Unpin and can still be moved normally
  • Self-referential types are generally !Unpin
  • Stack pinning: std::pin::pin!()
  • Heap pinning: Box::pin()

pin-project / pin-project-lite offers safe project to pinned structs into pinned fields without needing unsafe.

#[pin_project]
struct Timed<F> {
    #[pin]
    future: F,
    started_at: std::time::Instant,
}

impl<F: Future> Future for Timed<F> {
    type Output = F::Output;

    fn poll(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Self::Output> {
        // safely project `Pin<&mut Self>`
        let this = self.project();

        println!("elapsed: {:?}", this.started_at.elapsed());

        // `future` remains pinned
        this.future.poll(cx)
    }
}

.await, spawn(), join!() & select!{}

  • .await: Sequential concurrency within a task.
  • spawn(): Detach onto executor as independent task.
  • join!(): Drive multiple futures concurrently, wait for all.
  • select!{}: Race multiple branches, first completed branch wins, rest cancelled.

Warning

select!{} cancels losing branches by dropping their futures. Make sure every operation is cancellation-safe:

  • Avoid partially-consumed buffered IO
  • Avoid holding locks/resources across .await
  • Prefer restartable/idempotent operations
  • Manually free or drop any resource held in hand
let a = task_a();
let b = task_b();

let (a, b) = tokio::join!(a, b);
tokio::select! {
    v = socket.read() => { ... }
    _ = shutdown.recv() => { ... }
}

tokio::spawn_blocking()

Runs blocking or CPU-heavy synchronous work on Tokio’s dedicated blocking pool. Useful for:

  • Filesystem APIs lacking async variants
  • CPU-intensive computation
  • Legacy synchronous libraries
let result = tokio::task::spawn_blocking(|| {
    expensive_computation()
}).await?;