# async／await 基礎

`async`／`await` 讓程式在等待（網路、計時器、檔案）時先去做別的事；本頁說明 Future 是什麼、執行器扮演什麼角色、怎麼只用標準庫寫出最小執行器，以及它和執行緒的差別。

## async fn 與 Future

非同步（asynchronous）的核心想法是等待時不乾等：服務生點完一桌的餐，不會站在廚房門口等菜，而是先去幫下一桌點餐。

Rust 裡「一件還沒做完、之後可以繼續的工作」叫 Future（未來值），由 `Future` 特徵表示。`async fn` 和 `async { }` 區塊會讓編譯器自動產生 Future。API 細節見 [std::future](/pkg-future) 與 [std::task](/pkg-task)。

### async fn 回傳的是 Future，不會立刻執行

呼叫 `async fn` 只會得到一個 Future（像一張待辦單），要有人推動它（poll），本體才會開始跑。和 JavaScript 的 Promise 不同，Rust 的 Future 是惰性的。

標準庫沒有內建執行 Future 的工具，下面先寫一個陽春的 `block_on`：不斷 poll 直到完成（`Waker::noop` 為 Rust 1.85 起、`pin!` 為 Rust 1.68 起）。這種忙碌迴圈只適合示範，正式寫法在下一節。

範例：
```rust
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};

fn block_on<F: Future>(fut: F) -> F::Output {
    let mut fut = pin!(fut);
    let mut cx = Context::from_waker(Waker::noop());
    loop {
        if let Poll::Ready(value) = fut.as_mut().poll(&mut cx) {
            return value;
        }
    }
}

async fn greet(name: &str) -> String {
    println!("greet 開始執行");
    format!("哈囉，{name}")
}

fn main() {
    let fut = greet("Ann");
    println!("已呼叫 greet，但函式本體還沒執行");
    let message = block_on(fut);
    println!("結果：{message}");
}
```

輸出：
```text
已呼叫 greet，但函式本體還沒執行
greet 開始執行
結果：哈囉，Ann
```

### .await：在 async 裡等另一個 Future

在 `async` 範圍內對 Future 寫 `.await`，代表等它完成並取得結果。程式碼讀起來和同步程式一樣由上往下，但每個 `.await` 都是可以暫停、讓出執行權的點。

`async move { }` 和 `move` 閉包一樣取得捕捉變數的所有權（見[閉包](/closures-basics)）。

注意：`.await` 只能寫在 `async` 的範圍內；在一般的 `fn main` 裡寫 `.await` 會得到編譯錯誤 E0728。

範例：
```rust
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};

fn block_on<F: Future>(fut: F) -> F::Output {
    let mut fut = pin!(fut);
    let mut cx = Context::from_waker(Waker::noop());
    loop {
        if let Poll::Ready(value) = fut.as_mut().poll(&mut cx) {
            return value;
        }
    }
}

async fn price_of(item: &str) -> u32 {
    match item {
        "咖啡" => 60,
        "蛋糕" => 90,
        _ => 0,
    }
}

async fn checkout(items: &[&str]) -> u32 {
    let mut total = 0;
    for item in items {
        let price = price_of(item).await;
        println!("{item}：{price}");
        total += price;
    }
    total
}

fn main() {
    let discount = 10;
    let order = async move {
        let total = checkout(&["咖啡", "蛋糕"]).await;
        total - discount
    };
    println!("折扣後：{}", block_on(order));
}
```

輸出：
```text
咖啡：60
蛋糕：90
折扣後：140
```

## 執行器的角色

Future 自己不會動，負責呼叫 `poll`、並在適當時機再呼叫的程式叫執行器（executor）：

```mermaid
sequenceDiagram
    participant E as 執行器
    participant F as Future
    participant W as 背景工作
    E->>F: poll(cx)
    F->>W: 開始工作，交出 Waker
    F-->>E: Poll::Pending
    Note over E: 先去做別的事或休息
    W->>E: waker.wake()
    E->>F: 再 poll(cx)
    F-->>E: Poll::Ready(結果)
```

### poll：每次推一下，回答 Pending 或 Ready

`Future::poll` 回傳 `Poll::Pending`（還沒好）或 `Poll::Ready(值)`。下面手寫一個要 poll 三次才完成的 Future，用迴圈推它；`Context` 帶的 `Waker` 用什麼都不做的 `Waker::noop()`（Rust 1.85 起）。

範例：
```rust
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};

struct NeedsThreePolls {
    polls: u32,
}

impl Future for NeedsThreePolls {
    type Output = &'static str;

    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.polls += 1;
        if self.polls < 3 { Poll::Pending } else { Poll::Ready("完成") }
    }
}

fn main() {
    let mut fut = NeedsThreePolls { polls: 0 };
    let mut cx = Context::from_waker(Waker::noop());
    for round in 1..=3 {
        let result = Pin::new(&mut fut).poll(&mut cx);
        println!("第 {round} 次 poll：{:?}", result);
    }
}
```

輸出：
```text
第 1 次 poll：Pending
第 2 次 poll：Pending
第 3 次 poll：Ready("完成")
```

### 只用標準庫寫最小執行器

真正的執行器不會一直空轉 poll，而是：

1. poll 一次；得到 `Pending` 就讓執行緒休息（`thread::park`）
2. Future 把 `cx.waker()` 交給負責通知的一方
3. 對方完成時呼叫 `waker.wake()`，執行器被 `unpark` 叫醒，再 poll 一次

下面用 `Wake` 特徵把「叫醒目前執行緒」包成 `Waker`；`Delay` 第一次 poll 時開背景執行緒，50 毫秒後設旗標並 `wake`。

注意：`thread::park` 可能無故提早返回（spurious wakeup），醒來後要重新 poll，不能假設已完成。

範例：
```rust
use std::future::Future;
use std::pin::{Pin, pin};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};
use std::time::Duration;

struct ThreadWaker(Thread);

impl Wake for ThreadWaker {
    fn wake(self: Arc<Self>) {
        self.0.unpark();
    }
}

fn block_on<F: Future>(fut: F) -> F::Output {
    let mut fut = pin!(fut);
    let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
    let mut cx = Context::from_waker(&waker);
    loop {
        match fut.as_mut().poll(&mut cx) {
            Poll::Ready(value) => return value,
            Poll::Pending => thread::park(),
        }
    }
}

struct Delay {
    done: Arc<Mutex<bool>>,
    started: bool,
}

impl Future for Delay {
    type Output = &'static str;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if *self.done.lock().unwrap() {
            return Poll::Ready("背景工作完成");
        }
        if !self.started {
            self.started = true;
            println!("第一次 poll：還沒好，交出 Waker 並回傳 Pending");
            let done = Arc::clone(&self.done);
            let waker = cx.waker().clone();
            thread::spawn(move || {
                thread::sleep(Duration::from_millis(50));
                *done.lock().unwrap() = true;
                waker.wake();
            });
        }
        Poll::Pending
    }
}

fn main() {
    let result = block_on(async {
        let msg = Delay { done: Arc::new(Mutex::new(false)), started: false }.await;
        format!("被喚醒後再 poll：{msg}")
    });
    println!("{result}");
}
```

輸出：
```text
第一次 poll：還沒好，交出 Waker 並回傳 Pending
被喚醒後再 poll：背景工作完成
```

## 與執行緒的差別

### 一條執行緒輪流跑多個任務

[執行緒](/concurrency-threads)由作業系統隨時切換；async 任務則是在 `.await` 回傳 `Pending` 時「自願」讓出執行權，這叫協作式排程（cooperative scheduling）。因此一條執行緒就能輪流推進很多個任務。

下面的 `run_all` 一輪輪 poll 所有任務，完成的移除；`YieldNow` 第一次 poll 回傳 `Pending`，模擬要等待。兩個任務交錯前進，全都在 main 執行緒上。

範例：
```rust
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};
use std::thread;

struct YieldNow {
    yielded: bool,
}

impl Future for YieldNow {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
        if self.yielded {
            Poll::Ready(())
        } else {
            self.yielded = true;
            Poll::Pending
        }
    }
}

async fn task(name: &'static str, steps: u32) {
    for step in 1..=steps {
        println!("任務 {name} 步驟 {step}（執行緒：{}）", thread::current().name().unwrap());
        YieldNow { yielded: false }.await;
    }
}

fn run_all(mut tasks: Vec<Pin<Box<dyn Future<Output = ()>>>>) {
    let mut cx = Context::from_waker(Waker::noop());
    while !tasks.is_empty() {
        tasks.retain_mut(|t| t.as_mut().poll(&mut cx).is_pending());
    }
}

fn main() {
    run_all(vec![Box::pin(task("A", 3)), Box::pin(task("B", 2))]);
    println!("所有任務完成");
}
```

輸出：
```text
任務 A 步驟 1（執行緒：main）
任務 B 步驟 1（執行緒：main）
任務 A 步驟 2（執行緒：main）
任務 B 步驟 2（執行緒：main）
任務 A 步驟 3（執行緒：main）
所有任務完成
```

注意：任務必須肯讓。在 async 裡呼叫會阻塞的函式（`thread::sleep`、大量計算、同步 IO），同一條執行緒上的其他任務都會被卡住。

| 比較 | 執行緒 | async 任務 |
| --- | --- | --- |
| 誰負責切換 | 作業系統，隨時可能切換 | 執行器，只在 `.await` 讓出時切換 |
| 每個單位的成本 | 自己的堆疊，通常數 MB 虛擬記憶體 | 一個 Future 物件，通常幾百位元組 |
| 適合 | CPU 密集的計算、要用多核心 | 大量等待 IO 的工作，例如同時處理上萬條連線 |

## 常見執行環境：tokio

### 用 tokio 執行非同步程式

實際專案會用第三方 crate 提供的執行環境（runtime），最常見的是 tokio：多執行緒執行器加上非同步的計時器、網路與檔案 IO。不同 runtime 的 IO 型別通常不能混用，一個專案選一個。

注意：tokio 是第三方 crate，要在 `Cargo.toml` 加入相依（見 [Cargo.toml 與相依套件](/modules-cargo)）並用 `cargo run` 執行，不能用 `rustc` 單檔編譯。以下以 tokio 1.54.1 實際執行。

目錄結構：
```text
tokio-demo/
├── Cargo.toml
└── src/
    └── main.rs
```

`Cargo.toml`：
```toml
[package]
name = "tokio-demo"
version = "0.1.0"
edition = "2024"

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

`src/main.rs`：
```rust
use std::time::Duration;
use tokio::time::sleep;

async fn download(name: &str, ms: u64) -> String {
    sleep(Duration::from_millis(ms)).await;
    format!("{name} 下載完成")
}

#[tokio::main]
async fn main() {
    let (a, b) = tokio::join!(download("圖片", 200), download("影片", 100));
    println!("{a}");
    println!("{b}");

    let handles: Vec<_> = (1..=3)
        .map(|id| tokio::spawn(async move { id * 10 }))
        .collect();
    let mut results = Vec::new();
    for h in handles {
        results.push(h.await.unwrap());
    }
    println!("spawn 的結果：{:?}", results);
}
```

`#[tokio::main]` 建立 runtime 來執行 `async fn main`。`tokio::join!` 同時等待多個 Future，兩個下載共約 200 毫秒而非 300 毫秒，結果依參數順序回傳。`tokio::spawn` 像 `thread::spawn`，把任務交給 runtime，回傳可 `.await` 的 handle。

執行 `cargo run --quiet` 的輸出：
```text
圖片 下載完成
影片 下載完成
spawn 的結果：[10, 20, 30]
```

## 重點整理

- `async fn` 回傳 Future，呼叫時不執行本體；要有人 poll 才會跑
- `.await` 等待另一個 Future 完成，只能寫在 async 範圍內
- 執行器負責 poll；Future 回傳 `Pending` 時交出 `Waker`，事情好了用 `wake` 通知再 poll
- 標準庫只提供 `Future`、`Poll`、`Waker` 等基礎，執行器要自己寫或用 crate
- async 任務在 `.await` 自願讓出，一條執行緒就能跑很多任務，但不能在裡面阻塞
- 實務上用 tokio 這類 runtime，需在 `Cargo.toml` 加相依套件

## 資料來源

- [The Rust Programming Language（章節架構參考）](https://doc.rust-lang.org/book/)
- [The Rust Reference](https://doc.rust-lang.org/reference/)
- [Rust 標準庫文件](https://doc.rust-lang.org/std/)
- [Rust 官方部落格](https://blog.rust-lang.org/)
