显示页面讨论过去修订反向链接回到顶部 本页面只读。您可以查看源文件,但不能更改它。如果您觉得这是系统错误,请联系管理员。 # 33. 异步编程基础 ## 学习目标 - 理解异步编程与线程并发的区别。 - 掌握 `async fn`、`Future` 与 `.await` 的基本用法。 - 熟练使用 `.await?` 在异步函数中传播错误。 - 使用 `join!` 并发执行多个异步任务。 - 使用 `tokio::spawn` 创建异步任务。 - 避开 `.await?` 跳过善后逻辑等常见陷阱。 ## 33.1 为什么需要异步 第 32 章用线程实现并发:一个任务阻塞时,操作系统切换到另一个线程。但线程有成本——每个线程占用独立的栈内存,创建和切换都有开销。当任务数量达到成千上万(例如网络服务器处理海量连接),线程模型就扛不住了。 异步编程用**单线程轮询多个任务**的方式解决这个问题:任务在等待(I/O、定时器)时**主动让出**执行权,运行时可以立刻去跑其他任务。 | 对比项 | 线程并发 | 异步并发 | | 调度者 | 操作系统 | 异步运行时(如 tokio) | | 任务成本 | 高(MB 级栈) | 低(KB 级状态机) | | 适用场景 | CPU 密集计算 | I/O 密集(网络、文件、定时) | | 编程模型 | `thread::spawn` | `async fn` + `.await` | ## 33.2 `async fn` 与 `Future` 用 `async` 标记的函数不会立即执行,而是返回一个 `Future`("将来会完成的值"): ```rust async fn say_hello() -> String { String::from("hello") } fn main() { let fut = say_hello(); // 什么都不会发生!只是创建了一个 Future println!("Future 已创建,但还没执行"); } ``` `async fn say_hello() -> String` 的实际返回类型是 `impl Future<Output = String>`。Future 是惰性的:不被 `.await`,就永远不执行。 ## 33.3 `.await` 运算符 `.await` 等待一个 `Future` 完成并取出其中的值。**`.await` 只能在 `async` 函数或 `async` 块中使用**: ```rust async fn fetch_number() -> i32 { 42 } async fn use_it() { let n = fetch_number().await; // 等待完成,取出 i32 println!("拿到: {}", n); } ``` `.await` 让出的是**协作式**的执行权:当前任务在这里暂停,运行时可以去执行别的任务,等这个 `Future` 就绪后再回来继续。 `main` 函数默认不是 `async` 的,需要一个运行时来驱动。最常用的运行时是 tokio: ```rust // Cargo.toml: tokio = { version = "1", features = ["full"] } #[tokio::main] async fn main() { let n = fetch_number().await; println!("拿到: {}", n); } async fn fetch_number() -> i32 { 42 } ``` ## 33.4 `.await?`:异步中的错误传播 当 `Future` 的输出是 `Result<T, E>` 时,`.await` 拿到的是整个 `Result`,再接上第 21 章学过的 `?` 就能一步完成"等待 + 错误传播": ```rust async fn read_file(path: &str) -> Result<String, std::io::Error> { tokio::fs::read_to_string(path).await } async fn load_config() -> Result<String, std::io::Error> { let content = read_file("config.toml").await?; // ⬅ 先 .await 再 ? Ok(content) } ``` **执行顺序是从左到右:** ``` read_file("config.toml") → Future<Output = Result<String, io::Error>> .await → Result<String, io::Error> ? → Ok:取出 String 继续;Err:立即从 load_config 返回 ``` 等价于: ```rust let content = match read_file("config.toml").await { Ok(c) => c, Err(e) => return Err(e), // 出错时整个函数立刻返回 }; ``` 函数返回类型必须还是 `Result<T, E>`,`?` 才能把错误抛给调用者。链式调用也一样: ```rust let len = tokio::fs::read_to_string("a.txt").await?.len(); ``` ## 33.5 `join!` 并发执行多个异步任务 连续写两个 `.await` 是**串行**的——第二个任务要等第一个完成才开始。用 `tokio::join!` 可以真正并发: ```rust use tokio::time::{sleep, Duration}; async fn task_a() -> i32 { sleep(Duration::from_millis(100)).await; 1 } async fn task_b() -> i32 { sleep(Duration::from_millis(100)).await; 2 } #[tokio::main] async fn main() { // 串行:总共约 200ms let a = task_a().await; let b = task_b().await; // 并发:总共约 100ms,两个任务同时推进 let (a, b) = tokio::join!(task_a(), task_b()); println!("{} {}", a, b); } ``` ## 33.6 `tokio::spawn` 创建异步任务 `join!` 适合数量固定的任务。要把任务扔到后台独立运行,用 `tokio::spawn`,它返回一个 `JoinHandle`: ```rust #[tokio::main] async fn main() { let handle = tokio::spawn(async { sleep(Duration::from_millis(50)).await; 42 }); // 主任务可以继续做别的事…… let result = handle.await.unwrap(); // 等待任务结束并取回结果 println!("后台任务返回: {}", result); } ``` 与 `thread::spawn` 类似,`tokio::spawn` 的闭包通常也需要 `move`,且被移动的数据必须实现 `Send`——因为任务可能被运行时调度到任意线程上执行。 ## 33.7 异步中的共享状态 异步任务之间共享可变状态,同样使用 `Arc<Mutex<T>>`: ```rust use std::sync::Arc; use tokio::sync::Mutex; #[tokio::main] async fn main() { let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counter); let handle = tokio::spawn(async move { let mut num = counter.lock().await; // 异步锁:用 .await 而不是 unwrap *num += 1; }); handles.push(handle); } for handle in handles { handle.await.unwrap(); } println!("结果: {}", *counter.lock().await); } ``` 注意两点区别: 1. 异步代码用 `tokio::sync::Mutex`,加锁是 `lock().await`;标准库的 `std::sync::Mutex` 的锁会阻塞整个线程。 2. **不要**在持有锁的期间 `.await` 其他耗时操作,容易造成死锁或长时间占用。 ## 33.8 常见陷阱:`.await?` 跳过善后逻辑 `.await?` 方便,但它"出错就跑路"的特性会跳过函数里后续的所有代码。看这个反例: ```rust async fn execute_task(run_id: &str) -> Result<(), Error> { mark_running(run_id).await; run_task(run_id).await?; // ❌ 出错时直接返回! mark_success(run_id).await; Ok(()) } async fn mark_running(_id: &str) {} async fn mark_success(_id: &str) {} async fn run_task(_id: &str) -> Result<(), Error> { Err(Error) } ``` 如果 `run_task` 失败,`?` 会**立即从 `execute_task` 返回**: - 数据库里这个 run 的状态停留在 `running`,永远不被更新——**僵尸任务**; - 后续应执行的"标记失败、发出失败事件、通知前端"等善后逻辑全部被跳过。 正确写法是**先接住结果,做完善后,再决定是否传播**: ```rust async fn execute_task(run_id: &str) -> Result<(), Error> { mark_running(run_id).await; let result = run_task(run_id).await; // 先接住,不加 ? if let Err(e) = result { fail_run(run_id).await; // 善后:写 failed 状态 + 发事件 return Err(e); // 善后做完,再把错误传出去 } mark_success(run_id).await; Ok(()) } async fn fail_run(_id: &str) {} ``` 一句话总结:`?` 是"出错就跑路",善后逻辑是"临死前的遗言";跑路太快,遗言没说出口。凡是出错时**必须**执行的清理代码,都不能放在 `.await?` 之后。 ## 33.9 小结 | 概念 | 语法 | 说明 | | 定义异步函数 | `async fn f() -> T` | 返回 `Future`,惰性不执行 | | 等待完成 | `fut.await` | 取出 `Future` 中的值 | | 错误传播 | `fut.await?` | 等待 + 出错提前返回 | | 并发执行 | `tokio::join!(a(), b())` | 多个任务同时推进 | | 后台任务 | `tokio::spawn(async move { ... })` | 返回 `JoinHandle` | | 异步共享状态 | `Arc<tokio::sync::Mutex<T>>` | 用 `lock().await` 加锁 | | 入口 | `#[tokio::main]` | 让 `main` 支持 `async` | ## 33.10 思考题 1. 为什么说 `Future` 是"惰性"的?只调用 `async fn` 而不 `.await` 会发生什么? 2. `.await?` 的完整求值顺序是什么?如果函数返回类型不是 `Result`,`?` 还能用吗? 3. 把 33.8 的反例改成正确写法,并解释为什么修改后不会再出现"僵尸任务"。 4. `tokio::join!` 和连续两个 `.await` 在耗时上有什么区别?分别适用于什么场景? 登录 Detach Close 该主题尚不存在 您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。 rust/异步编程基础.txt 最后更改: 2026/08/12 23:59由 张叶安 登录