Sub topic 3
Pinning in Practice: Box::pin, `pin!`, and `Pin::as_mut`
Assume ownership, borrowing, traits, and basic async fn syntax. A future can be moved unless its type contains data that must stay at a fixed address.
Choosing a Pinning Method
Box::pin allocates a future on the heap and returns Pin<Box<T>>. Use it when a future must be stored or returned behind a stable pointer. The pin! macro pins a value on the stack. Use it for a local future.
Pin::as_mut creates a shorter Pin<&mut T> reborrow. It lets you poll or project a pinned value without moving the value itself.
use std::future::Future;
use std::pin::pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};
async fn add(a: u32, b: u32) -> u32 {
a + b
}
struct ThreadWaker(Thread);
impl Wake for ThreadWaker {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
fn block_on<F: Future>(future: F) -> F::Output {
let mut future = pin!(future);
let waker: Waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
let mut context = Context::from_waker(&waker);
loop {
match future.as_mut().poll(&mut context) {
Poll::Ready(value) => return value,
Poll::Pending => thread::park(),
}
}
}
fn main() {
let heap_future = Box::pin(add(1, 2));
let stack_future = pin!(add(3, 4));
println!("{}", block_on(heap_future));
println!("{}", block_on(stack_future));
}Projection and Composition
A pinned struct cannot freely expose mutable references to all its fields. Pin projection means safely accessing a pinned field. The pin-project crate generates this code and handles whether each field is pinned or movable.
Executors commonly provide three composition choices:
joinwaits for several futures and returns all results.selectwaits for the first future and cancels or returns the others.spawnputs a future in a separate task so the executor can schedule it independently.
Cancellation, `Send`, and Blocking
Dropping a future drops its state machine. If it is waiting at an .await, dropping it prevents later polling, so the operation is cancelled. Cleanup still runs through Drop, but external work may need explicit cancellation handling.
A future is Send only when the values it keeps across .await points are Send. Holding an Rc across an .await can make the future non-Send, preventing it from being spawned on a multi-threaded executor.
Blocking calls such as thread::sleep, synchronous file access, or long CPU work occupy an executor thread. Other tasks on that thread cannot run. Use asynchronous APIs or a runtime's spawn_blocking facility for unavoidable blocking work.
Exercise
When should you prefer Box::pin over pin!?
Show answer
Use Box::pin when the future must live on the heap, be returned, or be stored behind a trait object. Use pin! for a local stack value.