实现说明
手写 Future 的 poll 与迷你执行器可以归结为函数 wake、block_on、poll、main。
match 逐一列出值的可能形态,漏掉的分支编译器会拒绝。
使用要点
- 演示输出是带标签的(
poll、executor got:),每个操作都会留下自己的一行标注。 main的演示流程是block_on——跑一遍文件,这条流程从头到尾可见。
常见问题
运行「手写 Future 的 poll 与迷你执行器」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 poll、executor got: 标签标明各步骤。
主要签名是 fn wake(self: Arc<Self>)
核心语句
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();
}
}
代码示例
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}");
}