Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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
常见模式速查表

GoalUse
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 channels
Arc<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 速查

SituationUse
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, free
Pin::new(&mut val),安全且没有额外成本
Return a pinned trait object
返回一个被 pin 的 trait object
-> Pin<Box<dyn Future<Output = T> + Send>>

Channel Selection Guide
Channel 选型指南

ChannelProducersConsumersValuesUse When
mpscN1StreamWork queues, event buses
工作队列、事件总线
oneshot11SingleRequest/response, completion notification
请求响应、完成通知
broadcastNNAll recv allFan-out notifications, shutdown signals
扇出通知、停机信号
watch1NLatest onlyConfig updates, health status
配置更新、健康状态

Mutex Selection Guide
Mutex 选型指南

MutexUse When
std::sync::MutexLock is held briefly, never across .await
锁持有时间很短,而且绝对不会跨 .await
tokio::sync::MutexLock must be held across .await
锁需要跨 .await 持有。
parking_lot::MutexHigh contention, no .await, need performance
竞争激烈、没有 .await,并且特别看重性能。
tokio::sync::RwLockMany 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
常见报错与修复思路

ErrorCauseFix
future is not SendHolding !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 spawntokio::spawn requires 'static
tokio::spawn 要求 'static 生命周期。
Use Arc, clone(), or FuturesUnordered
使用 Arcclone(),或者改用 FuturesUnordered
the trait Future is not implemented for ()Missing .await
漏写了 .await
Add .await to the async call
给异步调用补上 .await
cannot borrow as mutable in pollSelf-referential borrow
发生了自引用借用问题。
Use Pin<&mut Self> correctly (see Ch. 4)
正确使用 Pin<&mut Self>,详见第 4 章。
Program hangs silentlyForgot to call waker.wake()
忘了调用 waker.wake()
Ensure every Pending path registers and triggers the waker
确保每条返回 Pending 的分支都注册并触发了 waker。

Further Reading
延伸阅读

ResourceWhy
Tokio TutorialOfficial hands-on guide — excellent for first projects
官方动手教程,非常适合第一个项目。
Async Book (official)Covers Future, Pin, Stream at the language level
从语言层面讲清 FuturePinStream
Jon Gjengset — Crust of Rust: async/await2-hour deep dive into internals with live coding
配合现场编码,深入讲解 async/await 内部机制。
Alice Ryhl — Actors with TokioProduction architecture pattern for stateful services
面向有状态服务的生产架构模式。
Without Boats — Pin, Unpin, and why Rust needs themThe original motivation from the language designer
语言设计者给出的原始动机说明。
Tokio mini-RedisComplete async Rust project — study-quality production code
一个完整的 async Rust 项目,学习价值很高。
Tower documentationMiddleware/service architecture used by axum, tonic, hyper
axum、tonic、hyper 等框架采用的中间件与服务架构。

End of Async Rust Training Guide
Async Rust 训练指南到此结束。