async/await 基礎

最後更新


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

async fn 與 Future


非同步(asynchronous)的核心想法是等待時不乾等:服務生點完一桌的餐,不會站在廚房門口等菜,而是先去幫下一桌點餐。
Rust 裡「一件還沒做完、之後可以繼續的工作」叫 Future(未來值),由 Future 特徵表示。async fn 和 async { } 區塊會讓編譯器自動產生 Future。API 細節見 std::future 與 std::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 起)。這種忙碌迴圈只適合示範,正式寫法在下一節。
範例:
  1. use std::future::Future;
  2. use std::pin::pin;
  3. use std::task::{Context, Poll, Waker};
  4. fn block_on<F: Future>(fut: F) -> F::Output {
  5. let mut fut = pin!(fut);
  6. let mut cx = Context::from_waker(Waker::noop());
  7. loop {
  8. if let Poll::Ready(value) = fut.as_mut().poll(&mut cx) {
  9. return value;
  10. }
  11. }
  12. }
  13. async fn greet(name: &str) -> String {
  14. println!("greet 開始執行");
  15. format!("哈囉,{name}")
  16. }
  17. fn main() {
  18. let fut = greet("Ann");
  19. println!("已呼叫 greet,但函式本體還沒執行");
  20. let message = block_on(fut);
  21. println!("結果:{message}");
  22. }

輸出:
  1. 已呼叫 greet,但函式本體還沒執行
  2. greet 開始執行
  3. 結果:哈囉,Ann

.await:在 async 裡等另一個 Future


在 async 範圍內對 Future 寫 .await,代表等它完成並取得結果。程式碼讀起來和同步程式一樣由上往下,但每個 .await 都是可以暫停、讓出執行權的點。
async move { } 和 move 閉包一樣取得捕捉變數的所有權(見閉包)。
注意:.await 只能寫在 async 的範圍內;在一般的 fn main 裡寫 .await 會得到編譯錯誤 E0728。
範例:
  1. use std::future::Future;
  2. use std::pin::pin;
  3. use std::task::{Context, Poll, Waker};
  4. fn block_on<F: Future>(fut: F) -> F::Output {
  5. let mut fut = pin!(fut);
  6. let mut cx = Context::from_waker(Waker::noop());
  7. loop {
  8. if let Poll::Ready(value) = fut.as_mut().poll(&mut cx) {
  9. return value;
  10. }
  11. }
  12. }
  13. async fn price_of(item: &str) -> u32 {
  14. match item {
  15. "咖啡" => 60,
  16. "蛋糕" => 90,
  17. _ => 0,
  18. }
  19. }
  20. async fn checkout(items: &[&str]) -> u32 {
  21. let mut total = 0;
  22. for item in items {
  23. let price = price_of(item).await;
  24. println!("{item}:{price}");
  25. total += price;
  26. }
  27. total
  28. }
  29. fn main() {
  30. let discount = 10;
  31. let order = async move {
  32. let total = checkout(&["咖啡", "蛋糕"]).await;
  33. total - discount
  34. };
  35. println!("折扣後:{}", block_on(order));
  36. }

輸出:
  1. 咖啡:60
  2. 蛋糕:90
  3. 折扣後:140

執行器的角色


Future 自己不會動,負責呼叫 poll、並在適當時機再呼叫的程式叫執行器(executor):
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(結果)
  1. sequenceDiagram
  2. participant E as 執行器
  3. participant F as Future
  4. participant W as 背景工作
  5. E->>F: poll(cx)
  6. F->>W: 開始工作,交出 Waker
  7. F-->>E: Poll::Pending
  8. Note over E: 先去做別的事或休息
  9. W->>E: waker.wake()
  10. E->>F: 再 poll(cx)
  11. F-->>E: Poll::Ready(結果)

poll:每次推一下,回答 Pending 或 Ready


Future::poll 回傳 Poll::Pending(還沒好)或 Poll::Ready(值)。下面手寫一個要 poll 三次才完成的 Future,用迴圈推它;Context 帶的 Waker 用什麼都不做的 Waker::noop()(Rust 1.85 起)。
範例:
  1. use std::future::Future;
  2. use std::pin::Pin;
  3. use std::task::{Context, Poll, Waker};
  4. struct NeedsThreePolls {
  5. polls: u32,
  6. }
  7. impl Future for NeedsThreePolls {
  8. type Output = &'static str;
  9. fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
  10. self.polls += 1;
  11. if self.polls < 3 { Poll::Pending } else { Poll::Ready("完成") }
  12. }
  13. }
  14. fn main() {
  15. let mut fut = NeedsThreePolls { polls: 0 };
  16. let mut cx = Context::from_waker(Waker::noop());
  17. for round in 1..=3 {
  18. let result = Pin::new(&mut fut).poll(&mut cx);
  19. println!("第 {round} 次 poll:{:?}", result);
  20. }
  21. }

輸出:
  1. 第 1 次 poll:Pending
  2. 第 2 次 poll:Pending
  3. 第 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,不能假設已完成。
範例:
  1. use std::future::Future;
  2. use std::pin::{Pin, pin};
  3. use std::sync::{Arc, Mutex};
  4. use std::task::{Context, Poll, Wake, Waker};
  5. use std::thread::{self, Thread};
  6. use std::time::Duration;
  7. struct ThreadWaker(Thread);
  8. impl Wake for ThreadWaker {
  9. fn wake(self: Arc<Self>) {
  10. self.0.unpark();
  11. }
  12. }
  13. fn block_on<F: Future>(fut: F) -> F::Output {
  14. let mut fut = pin!(fut);
  15. let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
  16. let mut cx = Context::from_waker(&waker);
  17. loop {
  18. match fut.as_mut().poll(&mut cx) {
  19. Poll::Ready(value) => return value,
  20. Poll::Pending => thread::park(),
  21. }
  22. }
  23. }
  24. struct Delay {
  25. done: Arc<Mutex<bool>>,
  26. started: bool,
  27. }
  28. impl Future for Delay {
  29. type Output = &'static str;
  30. fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
  31. if *self.done.lock().unwrap() {
  32. return Poll::Ready("背景工作完成");
  33. }
  34. if !self.started {
  35. self.started = true;
  36. println!("第一次 poll:還沒好,交出 Waker 並回傳 Pending");
  37. let done = Arc::clone(&self.done);
  38. let waker = cx.waker().clone();
  39. thread::spawn(move || {
  40. thread::sleep(Duration::from_millis(50));
  41. *done.lock().unwrap() = true;
  42. waker.wake();
  43. });
  44. }
  45. Poll::Pending
  46. }
  47. }
  48. fn main() {
  49. let result = block_on(async {
  50. let msg = Delay { done: Arc::new(Mutex::new(false)), started: false }.await;
  51. format!("被喚醒後再 poll:{msg}")
  52. });
  53. println!("{result}");
  54. }

輸出:
  1. 第一次 poll:還沒好,交出 Waker 並回傳 Pending
  2. 被喚醒後再 poll:背景工作完成

與執行緒的差別


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


執行緒由作業系統隨時切換;async 任務則是在 .await 回傳 Pending 時「自願」讓出執行權,這叫協作式排程(cooperative scheduling)。因此一條執行緒就能輪流推進很多個任務。
下面的 run_all 一輪輪 poll 所有任務,完成的移除;YieldNow 第一次 poll 回傳 Pending,模擬要等待。兩個任務交錯前進,全都在 main 執行緒上。
範例:
  1. use std::future::Future;
  2. use std::pin::Pin;
  3. use std::task::{Context, Poll, Waker};
  4. use std::thread;
  5. struct YieldNow {
  6. yielded: bool,
  7. }
  8. impl Future for YieldNow {
  9. type Output = ();
  10. fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
  11. if self.yielded {
  12. Poll::Ready(())
  13. } else {
  14. self.yielded = true;
  15. Poll::Pending
  16. }
  17. }
  18. }
  19. async fn task(name: &'static str, steps: u32) {
  20. for step in 1..=steps {
  21. println!("任務 {name} 步驟 {step}(執行緒:{})", thread::current().name().unwrap());
  22. YieldNow { yielded: false }.await;
  23. }
  24. }
  25. fn run_all(mut tasks: Vec<Pin<Box<dyn Future<Output = ()>>>>) {
  26. let mut cx = Context::from_waker(Waker::noop());
  27. while !tasks.is_empty() {
  28. tasks.retain_mut(|t| t.as_mut().poll(&mut cx).is_pending());
  29. }
  30. }
  31. fn main() {
  32. run_all(vec![Box::pin(task("A", 3)), Box::pin(task("B", 2))]);
  33. println!("所有任務完成");
  34. }

輸出:
  1. 任務 A 步驟 1(執行緒:main)
  2. 任務 B 步驟 1(執行緒:main)
  3. 任務 A 步驟 2(執行緒:main)
  4. 任務 B 步驟 2(執行緒:main)
  5. 任務 A 步驟 3(執行緒:main)
  6. 所有任務完成

注意:任務必須肯讓。在 async 裡呼叫會阻塞的函式(thread::sleep、大量計算、同步 IO),同一條執行緒上的其他任務都會被卡住。
比較執行緒async 任務
誰負責切換作業系統,隨時可能切換執行器,只在 .await 讓出時切換
每個單位的成本自己的堆疊,通常數 MB 虛擬記憶體一個 Future 物件,通常幾百位元組
適合CPU 密集的計算、要用多核心大量等待 IO 的工作,例如同時處理上萬條連線

常見執行環境:tokio


用 tokio 執行非同步程式


實際專案會用第三方 crate 提供的執行環境(runtime),最常見的是 tokio:多執行緒執行器加上非同步的計時器、網路與檔案 IO。不同 runtime 的 IO 型別通常不能混用,一個專案選一個。
注意:tokio 是第三方 crate,要在 Cargo.toml 加入相依(見 Cargo.toml 與相依套件)並用 cargo run 執行,不能用 rustc 單檔編譯。以下以 tokio 1.54.1 實際執行。
目錄結構:
  1. tokio-demo/
  2. ├── Cargo.toml
  3. └── src/
  4. └── main.rs

Cargo.toml:
  1. [package]
  2. name = "tokio-demo"
  3. version = "0.1.0"
  4. edition = "2024"
  5. [dependencies]
  6. tokio = { version = "1.54.1", features = ["full"] }

src/main.rs:
  1. use std::time::Duration;
  2. use tokio::time::sleep;
  3. async fn download(name: &str, ms: u64) -> String {
  4. sleep(Duration::from_millis(ms)).await;
  5. format!("{name} 下載完成")
  6. }
  7. #[tokio::main]
  8. async fn main() {
  9. let (a, b) = tokio::join!(download("圖片", 200), download("影片", 100));
  10. println!("{a}");
  11. println!("{b}");
  12. let handles: Vec<_> = (1..=3)
  13. .map(|id| tokio::spawn(async move { id * 10 }))
  14. .collect();
  15. let mut results = Vec::new();
  16. for h in handles {
  17. results.push(h.await.unwrap());
  18. }
  19. println!("spawn 的結果:{:?}", results);
  20. }

#[tokio::main] 建立 runtime 來執行 async fn main。tokio::join! 同時等待多個 Future,兩個下載共約 200 毫秒而非 300 毫秒,結果依參數順序回傳。tokio::spawn 像 thread::spawn,把任務交給 runtime,回傳可 .await 的 handle。
執行 cargo run --quiet 的輸出:
  1. 圖片 下載完成
  2. 影片 下載完成
  3. 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 加相依套件

資料來源