# Rust async/await 与 Tokio

多线程适合 CPU 密集，而 **async/await** 适合大量 IO 等待（网络、文件）。Tokio 是 Rust 最主流的异步运行时。

## 异步函数

`async fn` 返回一个「未来（Future）」，它本身不执行，需要运行时去驱动：

```rust
async fn fetch() -> String {
    // 模拟等待（真实场景是网络请求）
    "数据已获取".to_string()
}
```

## Tokio 启动

`Cargo.toml`：

```toml
[dependencies]
tokio = { version = "1", features = ["full"] }
```

`main` 用 `#[tokio::main]` 宏标记，内部自动起运行时：

```rust
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    let h1 = tokio::spawn(async {
        sleep(Duration::from_millis(100)).await;
        "任务A".to_string();
    });
    let h2 = tokio::spawn(async {
        "任务B".to_string();
    });

    let a = h1.await.unwrap();
    let b = h2.await.unwrap();
    println!("{} + {}", a, b);
}
```

## 关键点

- `.await` 会**让出**当前线程去干别的活，等到结果再继续——这就是高并发的来源。
- `tokio::spawn` 把异步任务丢进运行时调度。
- 一个线程能同时「跑」成千上万个等待中的任务。

## 小结

- `async fn` + `.await` 写异步代码，像写同步一样直观。
- Tokio 提供运行时、定时器、网络等能力。
- 选模型：CPU 密集用线程，IO 密集用 async。

➡️ [11. Axum Web 开发](/posts/language/rust-11-axum-web)

