Manual Future Poll With Mini Executor
A hand-written Future returns Pending twice with self-wakeups, and a block_on executor polls it until Ready using the std Wake trait to unpark the thread.
Code
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};
// 把 Waker 绑到当前线程:被唤醒时 unpark,执行器从 park 中恢复
struct ThreadWaker(Thread);
impl Wake for ThreadWaker {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
// 最小执行器:循环 poll,收到 Pending 就 park 等待唤醒
fn block_on<F: Future>(fut: F) -> F::Output {
let mut fut = Box::pin(fut);
let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
let mut cx = Context::from_waker(&waker);
loop {
match fut.as_mut().poll(&mut cx) {
Poll::Ready(value) => return value,
Poll::Pending => thread::park(),
}
}
}
// 手写 Future:前两次 poll 返回 Pending 并自我唤醒,第三次返回 Ready
struct RetryTwice {
polls: u32,
}
impl Future for RetryTwice {
type Output = &'static str;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.polls += 1;
if self.polls <= 2 {
println!("poll {} -> Pending", self.polls);
cx.waker().wake_by_ref(); // 立即重新排队,不必借助真实线程
return Poll::Pending;
}
Poll::Ready("finished")
}
}
fn main() {
let outcome = block_on(RetryTwice { polls: 0 });
println!("executor got: {outcome}");
}What the code does
Manual Future Poll With Mini Executor comes down to the functions wake, block_on, poll and main.
The match expression is exhaustive — the compiler enforces that no case is missing.
Caveats
- Any imports it has point exclusively at standard-library modules.
Using it
Signature: fn wake(self: Arc<Self>)
Output lines are prefixed (poll, executor got:), so every step’s effect is easy to pick out.
Treat main as the orchestrator calling block_on in a fixed order.
Key statements
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.polls += 1;
if self.polls <= 2 {
println!("poll {} -> Pending", self.polls);
cx.waker().wake_by_ref(); // 立即重新排队,不必借助真实线程
return Poll::Pending;
}
Poll::Ready("finished")
}
match fut.as_mut().poll(&mut cx) {
Poll::Ready(value) => return value,
Poll::Pending => thread::park(),
}
impl Wake for ThreadWaker {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
Interactive Tools for This Topic
FAQ
- What does Manual Future Poll With Mini Executor print when run?
- The script runs standalone; its 2 labeled outputs include `poll`, `executor got:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.