Rust 异步编程入门
理解 async/await 语法和 Future trait 实现并发的基本方法 · 难度:入门 · +15XP
异步编程概念
Rust 的异步编程基于 Future trait,允许在等待 I/O 操作时暂停当前任务,让出线程执行其他任务,实现高效并发。
async/await 语法
async fn 定义一个返回 Future 的异步函数:
use std::time::Duration;
async fn do_something() -> String {
// 模拟异步操作(如网络请求)
tokio::time::sleep(Duration::from_secs(1)).await;
"完成".to_string()
}
#[tokio::main]
async fn main() {
let result = do_something().await;
println!("{}", result);
}
Future trait
Future trait 的核心是 poll 方法,返回 Poll<T> 枚举:
| 变体 | 说明 |
|---|---|
| Poll::Ready(val) | Future 已完成,返回结果 |
| Poll::Pending | Future 未完成,稍后再次 poll |
use std::task::{Context, Poll};
use std::pin::Pin;
struct MyFuture {
ready: bool,
value: i32,
}
impl Future for MyFuture {
type Output = i32;
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<i32> {
if self.ready {
Poll::Ready(self.value)
} else {
Poll::Pending
}
}
}
运行时与执行器
异步代码需要运行时驱动,常用运行时:
- Tokio:功能最全,支持网络、文件等
- async-std:API 接近标准库
- smol:轻量级运行时
组合多个 Future
使用 join! 宏同时等待多个 Future:
use tokio::join;
async fn task1() { /* ... */ }
async fn task2() { /* ... */ }
#[tokio::main]
async fn main() {
join!(task1(), task2()); // 并发执行
}
练习提示: 编写两个异步函数,分别模拟下载图片和处理数据,使用 join! 让它们同时运行,并收集结果。