std::future

最後更新


定義「未來才會完成的值」:Future 特徵(trait),也是 async/.await 的基礎。

這個模組做什麼


Future 代表一個「還沒算完的工作」,例如等網路回應、等計時器。和執行緒不同,Future 本身不會自己跑:要有人反覆呼叫它的 poll 方法問「好了沒?」,它回答 Poll::Ready(值) 或 Poll::Pending。負責呼叫 poll 的程式叫做執行器(executor)。
名稱用途
Future 特徵定義 poll,所有非同步工作的共同介面
async fn、async { }編譯器自動產生 Future 的語法
.await在 async 裡等待另一個 Future 完成
ready(v)立刻完成的 Future
pending()永遠不會完成的 Future
poll_fn(f)用閉包臨時做出一個 Future
IntoFuture可以被 .await 的型別

標準庫沒有內建執行器。實務上會用第三方執行環境,本頁只用標準庫,自己寫一個最小的 block_on 來執行範例。poll 用到的 Context、Waker、Poll 定義在 std::task;poll 的 self 必須是 Pin<&mut Self>,原因見 std::pin。

匯入


  1. use std::future::{Future, ready, pending, poll_fn};
  2. use std::task::{Context, Poll};

Future 與 IntoFuture 從 Rust 2024 版次起已在 prelude 中(std::future::Future),寫 use 也不會出錯。

常用 API


Future 特徵:poll 與 Poll


Future 只有一個必要方法 poll,以及關聯型別 Output(完成後產生的值)。下面手動實作一個「需要被問兩次才完成」的 Future,並用 Waker::noop()(Rust 1.85 起,一個什麼都不做的喚醒器)親自呼叫 poll,看看執行器實際在做什麼。
簽名:
  1. pub trait Future {
  2. type Output;
  3. fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
  4. }

範例:
  1. use std::future::Future;
  2. use std::pin::Pin;
  3. use std::task::{Context, Poll, Waker};
  4. struct Download {
  5. progress: u32,
  6. }
  7. impl Future for Download {
  8. type Output = &'static str;
  9. fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
  10. self.progress += 50;
  11. if self.progress >= 100 {
  12. Poll::Ready("下載完成")
  13. } else {
  14. Poll::Pending
  15. }
  16. }
  17. }
  18. fn main() {
  19. let mut fut = Download { progress: 0 };
  20. let mut cx = Context::from_waker(Waker::noop());
  21. for round in 1..=3 {
  22. let r = Pin::new(&mut fut).poll(&mut cx);
  23. println!("第 {round} 次 poll:{:?}", r);
  24. if r.is_ready() {
  25. break;
  26. }
  27. }
  28. }

輸出:
  1. 第 1 次 poll:Pending
  2. 第 2 次 poll:Ready("下載完成")

注意:一個 Future 回傳 Ready 之後就不應再被 poll;再 poll 的行為由實作決定,async 產生的 Future 會 panic。

自己寫最小執行器:block_on


執行器的工作:反覆 poll Future,回傳 Pending 時先休息,等 Future 透過 Waker 通知「可以再問了」才繼續。最小版本用目前執行緒當工作者:休息用 thread::park(),喚醒用 unpark()。Wake 特徵讓一個用 Arc 包起來的結構直接變成 Waker,細節見 std::task。
簽名:
  1. fn block_on<F: Future>(fut: F) -> F::Output

範例:
  1. use std::future::Future;
  2. use std::pin::pin;
  3. use std::sync::Arc;
  4. use std::task::{Context, Poll, Wake, Waker};
  5. use std::thread::{self, Thread};
  6. struct ThreadWaker(Thread);
  7. impl Wake for ThreadWaker {
  8. fn wake(self: Arc<Self>) {
  9. self.0.unpark();
  10. }
  11. }
  12. fn block_on<F: Future>(fut: F) -> F::Output {
  13. let mut fut = pin!(fut);
  14. let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
  15. let mut cx = Context::from_waker(&waker);
  16. loop {
  17. match fut.as_mut().poll(&mut cx) {
  18. Poll::Ready(v) => return v,
  19. Poll::Pending => thread::park(),
  20. }
  21. }
  22. }
  23. fn main() {
  24. let answer = block_on(async { 6 * 7 });
  25. println!("答案是 {answer}");
  26. }

輸出:
  1. 答案是 42

thread::park 可能無故醒來,但這沒關係:醒來後只是多 poll 一次,Future 沒好就再回傳 Pending。之後的範例都會沿用這個 block_on。

async fn 與 async 區塊:自動產生 Future


async fn 呼叫後不會馬上執行函式本體,而是回傳一個 Future;async { } 區塊也一樣。只有被 poll(例如交給 block_on 或被 .await)時才開始跑。這叫做惰性(lazy)。
簽名:
  1. async fn name(args) -> T
  2. fn name(args) -> impl Future<Output = T>

範例:
  1. use std::future::Future;
  2. use std::pin::pin;
  3. use std::sync::Arc;
  4. use std::task::{Context, Poll, Wake, Waker};
  5. use std::thread::{self, Thread};
  6. struct ThreadWaker(Thread);
  7. impl Wake for ThreadWaker {
  8. fn wake(self: Arc<Self>) {
  9. self.0.unpark();
  10. }
  11. }
  12. fn block_on<F: Future>(fut: F) -> F::Output {
  13. let mut fut = pin!(fut);
  14. let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
  15. let mut cx = Context::from_waker(&waker);
  16. loop {
  17. match fut.as_mut().poll(&mut cx) {
  18. Poll::Ready(v) => return v,
  19. Poll::Pending => thread::park(),
  20. }
  21. }
  22. }
  23. async fn add(a: i32, b: i32) -> i32 {
  24. println!(" add 開始執行");
  25. a + b
  26. }
  27. fn main() {
  28. let fut = add(2, 3);
  29. println!("已呼叫 add,但還沒執行");
  30. let block = async {
  31. println!(" 區塊開始執行");
  32. "區塊結果"
  33. };
  34. println!("結果:{}", block_on(fut));
  35. println!("結果:{}", block_on(block));
  36. }

輸出:
  1. 已呼叫 add,但還沒執行
  2. add 開始執行
  3. 結果:5
  4. 區塊開始執行
  5. 結果:區塊結果

.await:串接多個 Future


在 async 函式或區塊裡,expr.await 會等 expr 這個 Future 完成並取得結果。如果它還沒好,整個外層 Future 也回傳 Pending,下次被 poll 時從同一個位置繼續。這讓非同步程式寫起來像一般的循序程式。
注意:.await 只能用在 async 的上下文中;在一般 fn main 裡要交給執行器。
簽名:
  1. future.await

範例:
  1. use std::future::Future;
  2. use std::pin::pin;
  3. use std::sync::Arc;
  4. use std::task::{Context, Poll, Wake, Waker};
  5. use std::thread::{self, Thread};
  6. struct ThreadWaker(Thread);
  7. impl Wake for ThreadWaker {
  8. fn wake(self: Arc<Self>) {
  9. self.0.unpark();
  10. }
  11. }
  12. fn block_on<F: Future>(fut: F) -> F::Output {
  13. let mut fut = pin!(fut);
  14. let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
  15. let mut cx = Context::from_waker(&waker);
  16. loop {
  17. match fut.as_mut().poll(&mut cx) {
  18. Poll::Ready(v) => return v,
  19. Poll::Pending => thread::park(),
  20. }
  21. }
  22. }
  23. async fn fetch_price(item: &str) -> u32 {
  24. match item {
  25. "咖啡" => 60,
  26. "蛋糕" => 85,
  27. _ => 0,
  28. }
  29. }
  30. async fn order(items: &[&str]) -> u32 {
  31. let mut total = 0;
  32. for item in items {
  33. let p = fetch_price(item).await;
  34. println!("{item}:{p}");
  35. total += p;
  36. }
  37. total
  38. }
  39. fn main() {
  40. let total = block_on(order(&["咖啡", "蛋糕"]));
  41. println!("合計 {total}");
  42. }

輸出:
  1. 咖啡:60
  2. 蛋糕:85
  3. 合計 145

ready 與 pending:現成的 Future


ready(v) 第一次被 poll 就回傳 Ready(v),適合在需要 Future 的地方直接給值。pending() 永遠回傳 Pending,常用於測試或表示「永遠不會發生的事件」。
簽名:
  1. pub fn ready<T>(t: T) -> Ready<T>
  2. pub fn pending<T>() -> Pending<T>

範例:
  1. use std::future::{Future, pending, ready};
  2. use std::pin::pin;
  3. use std::task::{Context, Waker};
  4. fn main() {
  5. let mut cx = Context::from_waker(Waker::noop());
  6. let mut a = pin!(ready("快取命中"));
  7. println!("{:?}", a.as_mut().poll(&mut cx));
  8. let mut b = pin!(pending::<i32>());
  9. println!("{:?}", b.as_mut().poll(&mut cx));
  10. println!("{:?}", b.as_mut().poll(&mut cx));
  11. }

輸出:
  1. Ready("快取命中")
  2. Pending
  3. Pending

poll_fn:用閉包做 Future


poll_fn(Rust 1.64 起)把一個「接收 &mut Context、回傳 Poll」的閉包包成 Future,不必另外定義結構。下面做出一個第三次 poll 才完成的 Future;每次回傳 Pending 前都呼叫 wake_by_ref(),請執行器馬上再 poll 一次。
注意:回傳 Pending 卻從不安排喚醒,搭配會 park 的執行器就會永遠卡住。
簽名:
  1. pub fn poll_fn<T, F>(f: F) -> PollFn<F>
  2. where F: FnMut(&mut Context<'_>) -> Poll<T>

範例:
  1. use std::future::{Future, poll_fn};
  2. use std::pin::pin;
  3. use std::sync::Arc;
  4. use std::task::{Context, Poll, Wake, Waker};
  5. use std::thread::{self, Thread};
  6. struct ThreadWaker(Thread);
  7. impl Wake for ThreadWaker {
  8. fn wake(self: Arc<Self>) {
  9. self.0.unpark();
  10. }
  11. }
  12. fn block_on<F: Future>(fut: F) -> F::Output {
  13. let mut fut = pin!(fut);
  14. let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
  15. let mut cx = Context::from_waker(&waker);
  16. loop {
  17. match fut.as_mut().poll(&mut cx) {
  18. Poll::Ready(v) => return v,
  19. Poll::Pending => thread::park(),
  20. }
  21. }
  22. }
  23. fn main() {
  24. let mut tries = 0;
  25. let fut = poll_fn(|cx| {
  26. tries += 1;
  27. println!("第 {tries} 次被 poll");
  28. if tries < 3 {
  29. cx.waker().wake_by_ref();
  30. Poll::Pending
  31. } else {
  32. Poll::Ready(tries * 100)
  33. }
  34. });
  35. println!("結果 {}", block_on(fut));
  36. }

輸出:
  1. 第 1 次被 poll
  2. 第 2 次被 poll
  3. 第 3 次被 poll
  4. 結果 300

IntoFuture:讓自訂型別可以 .await


.await 實際上會先呼叫 IntoFuture::into_future。所有 Future 自動實作 IntoFuture;你也可以替「設定好參數的請求建構器」之類的型別實作它,讓使用者直接 .await 而不必多呼叫一個 send()。
簽名:
  1. pub trait IntoFuture {
  2. type Output;
  3. type IntoFuture: Future<Output = Self::Output>;
  4. fn into_future(self) -> Self::IntoFuture;
  5. }

範例:
  1. use std::future::{Future, IntoFuture, Ready, ready};
  2. use std::pin::pin;
  3. use std::task::{Context, Poll, Waker};
  4. struct Query {
  5. table: &'static str,
  6. limit: usize,
  7. }
  8. impl IntoFuture for Query {
  9. type Output = String;
  10. type IntoFuture = Ready<String>;
  11. fn into_future(self) -> Ready<String> {
  12. ready(format!("SELECT * FROM {} LIMIT {}", self.table, self.limit))
  13. }
  14. }
  15. fn main() {
  16. let task = async { Query { table: "users", limit: 5 }.await };
  17. let mut task = pin!(task);
  18. let mut cx = Context::from_waker(Waker::noop());
  19. if let Poll::Ready(sql) = task.as_mut().poll(&mut cx) {
  20. println!("{sql}");
  21. }
  22. }

輸出:
  1. SELECT * FROM users LIMIT 5

重點整理


  • Future 是「被 poll 才會前進」的工作,poll 回傳 Poll::Ready(值) 或 Poll::Pending
  • async fn 與 async { } 是惰性的:呼叫只產生 Future,交給執行器或 .await 才執行
  • 標準庫不含執行器;最小的 block_on 用 pin!、Wake、thread::park 就能寫出來
  • 回傳 Pending 時必須安排日後呼叫 Waker,否則執行器不會再 poll
  • ready、pending、poll_fn 可快速做出 Future;實作 IntoFuture 讓自訂型別支援 .await