expression

Pinning async state across suspension

A compiler-generated future may keep borrows across suspension, so generic polling uses a pinned receiver. The example holds a local borrow across a single bounded self-notified suspension. The driver accepts only this known immediate wake pattern; it is not a general executor. Expected stdout (not executed): Pending Ready(2) Common mistake: Assuming every async future implements Unpin or moving a pinned future out of its storage.

Formal Syntax & Structure

rust syntaxrust
Future::poll(self: Pin<&mut Self>, cx: &mut Context<'_>)

Working Example

Example Snippetrust
fn main() {    use std::{future::{Future, poll_fn}, task::{Context, Poll, Wake, Waker}, sync::{Arc, atomic::{AtomicBool, Ordering}}};    struct Signal(AtomicBool);    impl Wake for Signal { fn wake(self: Arc<Self>) { self.0.store(true, Ordering::SeqCst); } }    let signal = Arc::new(Signal(AtomicBool::new(false)));    let w = Waker::from(signal.clone());    let mut cx = Context::from_waker(&w);    let mut f = Box::pin(async {        let text = String::from("seed");        let part = &text[..2];        let mut first = true;        poll_fn(|cx| {            if first { first = false; cx.waker().wake_by_ref(); Poll::Pending }            else { Poll::Ready(()) }        }).await;        part.len()    });    println!("{:?}", f.as_mut().poll(&mut cx));    assert!(signal.0.load(Ordering::SeqCst));    println!("{:?}", f.as_mut().poll(&mut cx));}
Rust Reference