Rust 的 async 不是魔法:Future 就是一个被 poll 的状态机。这篇不借助任何运行时,自己写 poll 循环,把「惰性」「Pending 与 Ready」「await 向上传 Pending」「drop 一个 Future」都亲眼跑出来。
编译:成功
运行(退出码 0):
调用 hello():
拿到了 Future(1 字节),函数体还没有运行
第一次 poll:
hello() 的函数体开始执行
poll 返回 Ready(42) 编译:成功
运行(退出码 0):
第 1 次 poll → Pending(剩 3)
第 2 次 poll → Pending(剩 2)
第 3 次 poll → Pending(剩 1)
第 4 次 poll → Ready
最终得到 4async runtime 做的事见Async Runtime 做了什么。
编译:成功
运行(退出码 0):
外层第 1 次 poll:
A 开始
→ Pending
外层第 2 次 poll:
→ Pending
外层第 3 次 poll:
A 结束
B 开始
→ Pending
外层第 4 次 poll:
B 结束
→ Ready("全部完成")async fn 生成的状态机见async/await 状态机。
编译:成功
运行(退出码 0):
创建后直接 drop(没 poll):
poll 一次后 drop:
work(half) 开始
准备 drop Future
Noisy(half) 被 drop取消语义见Future 取消与 Drop。
源码:
1 | async fn f() -> i32 { 1 }
2 | async fn g() { f(); }
3 | fn main() { let _ = g(); }
编译:成功;警告:
warning: unused implementer of `Future` that must be used
--> <实验目录>/src/u96e.rs:2:16
|
2 | async fn g() { f(); }
| ^^^
|
= note: futures do nothing unless you `.await` or poll them
= note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default
warning: 1 warning emitted
运行(退出码 0):
(无输出)