Sub topic 2
Context and Waker: How a Future Asks to Be Polled Again
This chapter assumes ownership, borrowing, lifetimes, traits, enums, basic threads, and simple async fn code.
Context and Waker
A future may need to wait for an event, such as a socket becoming readable. It returns Poll::Pending instead of blocking. The executor must know when to poll it again.
Context gives the future access to a Waker. A waker is a handle that tells the executor, “this future may be ready now.” The future registers or stores the waker with the operation it is waiting for, then returns Pending.
flowchart TD
A[Executor calls poll] --> B{Is the future ready?}
B -->|Yes| C[Return Ready]
B -->|No| D[Save the Waker]
D --> E[Return Pending]
E --> F[External event occurs]
F --> G[Waker wakes the task]
G --> AWriting a Future by Hand
The Future trait describes this protocol:
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
struct CountDown(u32);
impl Future for CountDown {
type Output = &'static str;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.0 == 0 {
Poll::Ready("done")
} else {
self.0 -= 1;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}This example wakes itself so an executor polls it again. Real futures usually wake when I/O or another event completes.
Why Moving a Future Can Be Unsafe
The compiler represents an async function as a state machine. After an .await, that state machine can hold references to its own stored values. Moving it would invalidate those references.
Pin: Promising a Value Will Not Move
Pin<P> wraps a pointer-like type P and prevents the pointed-to value from moving through that pointer. A future’s poll method receives Pin<&mut Self> for this reason.
Pin does not make every field immutable. It only restricts moves that could violate a type’s pinning requirements.
`Unpin` and `PhantomPinned`
Most Rust types implement Unpin, which means they remain safe to move even when accessed through Pin. A self-referential type can opt out by containing PhantomPinned.
use std::marker::PhantomPinned;
use std::pin::Pin;
struct SelfRef {
text: String,
pointer: *const String,
_pin: PhantomPinned,
}
fn make() -> Pin<Box<SelfRef>> {
let mut value = Box::pin(SelfRef {
text: String::from("hello"),
pointer: std::ptr::null(),
_pin: PhantomPinned,
});
let pointer = &value.text as *const String;
unsafe {
value.as_mut().get_unchecked_mut().pointer = pointer;
}
value
}The value is pinned before its internal pointer is initialized, and it must not move afterward.
Exercise
Why must a future save the waker before returning Poll::Pending?
Show answer
The waker gives the executor a way to schedule another poll when the future's awaited event becomes ready.