Summary and Reference Card
总结与参考卡片
Quick Reference Card
快速参考卡片
Async Mental Model
Async 心智模型
┌─────────────────────────────────────────────────────┐
│ async fn → State Machine (enum) → impl Future │
│ .await → poll() the inner future │
│ executor → loop { poll(); sleep_until_woken(); } │
│ waker → "hey executor, poll me again" │
│ Pin → "promise I won't move in memory" │
└─────────────────────────────────────────────────────┘
可以把整套 async 先记成这一句话:async fn 会被编译成状态机,.await 会去 poll 内层 future,executor 负责不断轮询并在被唤醒后继续推进,waker 用来通知执行器“我又能继续了”,而 Pin 保证状态机不会在内存里乱挪位置。
Common Patterns Cheat Sheet
常见模式速查表
| Goal | Use |
|---|---|
| Run two futures concurrently 让两个 future 并发执行 | tokio::join!(a, b) |
| Race two futures 让两个 future 竞速 | tokio::select! { ... } |
| Spawn a background task 启动后台任务 | tokio::spawn(async { ... }) |
| Run blocking code in async 在 async 上下文中执行阻塞代码 | tokio::task::spawn_blocking(|| { ... }) |
| Limit concurrency 限制并发数 | Semaphore::new(N) |
| Collect many task results 收集大量任务结果 | JoinSet |
| Share state across tasks 在任务之间共享状态 | Arc<Mutex<T>> or channelsArc<Mutex<T>> 或 channel |
| Graceful shutdown 优雅停机 | watch::channel + select! |
| Process a stream N-at-a-time 按 N 个一组处理 stream | .buffer_unordered(N) |
| Timeout a future 给 future 设置超时 | tokio::time::timeout(dur, fut) |
| Retry with backoff 带退避的重试 | Custom combinator (see Ch. 13) 自定义组合器,见第 13 章 |
Pinning Quick Reference
Pinning 速查
| Situation | Use |
|---|---|
| Pin a future on the heap 把 future 固定在堆上 | Box::pin(fut) |
| Pin a future on the stack 把 future 固定在栈上 | tokio::pin!(fut) |
Pin an Unpin type固定一个 Unpin 类型 | Pin::new(&mut val) — safe, freePin::new(&mut val),安全且没有额外成本 |
| Return a pinned trait object 返回一个被 pin 的 trait object | -> Pin<Box<dyn Future<Output = T> + Send>> |
Channel Selection Guide
Channel 选型指南
| Channel | Producers | Consumers | Values | Use When |
|---|---|---|---|---|
mpsc | N | 1 | Stream | Work queues, event buses 工作队列、事件总线 |
oneshot | 1 | 1 | Single | Request/response, completion notification 请求响应、完成通知 |
broadcast | N | N | All recv all | Fan-out notifications, shutdown signals 扇出通知、停机信号 |
watch | 1 | N | Latest only | Config updates, health status 配置更新、健康状态 |
Mutex Selection Guide
Mutex 选型指南
| Mutex | Use When |
|---|---|
std::sync::Mutex | Lock is held briefly, never across .await锁持有时间很短,而且绝对不会跨 .await。 |
tokio::sync::Mutex | Lock must be held across .await锁需要跨 .await 持有。 |
parking_lot::Mutex | High contention, no .await, need performance竞争激烈、没有 .await,并且特别看重性能。 |
tokio::sync::RwLock | Many readers, few writers, locks cross .await读多写少,而且锁要跨 .await。 |
Decision Quick Reference
决策速查
Need concurrency?
├── I/O-bound → async/await
├── CPU-bound → rayon / std::thread
└── Mixed → spawn_blocking for CPU parts
Choosing runtime?
├── Server app → tokio
├── Library → runtime-agnostic (futures crate)
├── Embedded → embassy
└── Minimal → smol
Need concurrent futures?
├── Can be 'static + Send → tokio::spawn
├── Can be 'static + !Send → LocalSet
├── Can't be 'static → FuturesUnordered
└── Need to track/abort → JoinSet
如果只是为了快速判断,先按这个顺序想:先分清是 I/O 密集还是 CPU 密集,再决定运行时,最后再看 future 的生命周期和 Send 约束。
Common Error Messages and Fixes
常见报错与修复思路
| Error | Cause | Fix |
|---|---|---|
future is not Send | Holding !Send type across .await在 .await 之前持有了 !Send 类型。 | Scope the value so it’s dropped before .await, or use current_thread runtime缩小作用域,让它在 .await 之前被释放,或者改用 current_thread 运行时。 |
borrowed value does not live long enough in spawn | tokio::spawn requires 'statictokio::spawn 要求 'static 生命周期。 | Use Arc, clone(), or FuturesUnordered使用 Arc、clone(),或者改用 FuturesUnordered。 |
the trait Future is not implemented for () | Missing .await漏写了 .await。 | Add .await to the async call给异步调用补上 .await。 |
cannot borrow as mutable in poll | Self-referential borrow 发生了自引用借用问题。 | Use Pin<&mut Self> correctly (see Ch. 4)正确使用 Pin<&mut Self>,详见第 4 章。 |
| Program hangs silently | Forgot to call waker.wake()忘了调用 waker.wake()。 | Ensure every Pending path registers and triggers the waker确保每条返回 Pending 的分支都注册并触发了 waker。 |
Further Reading
延伸阅读
| Resource | Why |
|---|---|
| Tokio Tutorial | Official hands-on guide — excellent for first projects 官方动手教程,非常适合第一个项目。 |
| Async Book (official) | Covers Future, Pin, Stream at the language level从语言层面讲清 Future、Pin 和 Stream。 |
| Jon Gjengset — Crust of Rust: async/await | 2-hour deep dive into internals with live coding 配合现场编码,深入讲解 async/await 内部机制。 |
| Alice Ryhl — Actors with Tokio | Production architecture pattern for stateful services 面向有状态服务的生产架构模式。 |
| Without Boats — Pin, Unpin, and why Rust needs them | The original motivation from the language designer 语言设计者给出的原始动机说明。 |
| Tokio mini-Redis | Complete async Rust project — study-quality production code 一个完整的 async Rust 项目,学习价值很高。 |
| Tower documentation | Middleware/service architecture used by axum, tonic, hyper axum、tonic、hyper 等框架采用的中间件与服务架构。 |
End of Async Rust Training Guide
Async Rust 训练指南到此结束。