Rust 异步编程
核对 Rust Future 惰性抽象与 async/await 语法、Tokio/async-std 异步运行时执行模型、async 块与 .await? 错误传播、异步 trait 方法、并发任务与异步 I/O 通道。
学完这一章,你能够
- 核对 Rust Future 惰性抽象与 async/await 语法、Tokio/async-std 异步运行时执行模型、async 块与 .await? 错误传播、异步 trait 方法、并发任务与异步 I/O 通道。
异步编程模型、Future 与 async/await 基础实例
异步编程让程序在等待文件读写或网络通信等慢速 I/O 时让出执行权,无需阻塞操作系统线程,从而大幅提升高并发吞吐与响应速度。Rust 异步生态由两部分协同构成:语言与标准库层提供 `Future` trait(代表尚未完成、需被轮询推进的惰性计算)及 `async`/`await` 语法;第三方异步运行时(如 `tokio`、`async-std`、`futures`)负责事件循环、定时器与任务调度。
在典型 Tokio 定时任务示例中,`async fn async_task() -> u32` 调用 `tokio::time::sleep(Duration::from_secs(1)).await`(注:Tokio 1.x 已用 `time::sleep` 替代早期 0.2 版本的 `delay_for`)随后返回 `42`;外层 `execute_async_task()` 通过 `.await` 等待结果并打印,入口使用 `#[tokio::main]` 属性宏初始化运行时,依次输出 `Start executing async task...`、`Async task result: 42` 与 `Async task completed!`。
在异步网络请求示例中,结合 `tokio::runtime::Runtime::new()` 与 `reqwest::get(url).await?` 可编写 `async fn fetch_url(url: &str) -> Result<String, Box<dyn Error>>`,在同步 `main` 函数中通过 `rt.block_on(execute_async_task())` 驱动执行并匹配处理成功或错误结果。本站离线校验器使用 `asyncio` 配合本地离线桩与 `PollCounterFuture` 完整验证了惰性轮询(`Pending -> Pending -> Ready(42)`)、任务日志顺序及离线抓取返回流程(不访问任何外部网络)。
async / await / 异步块 / 执行器与 .await? 错误传播
`async fn hello() -> String` 或 `async fn add(a: i32, b: i32) -> i32` 并非立即执行函数体,而是返回一个实现 `impl Future<Output = T>` 的匿名状态机;只有当调用方在异步上下文中施加 `.await`(如 `let result = hello().await;`)时,才会暂停当前任务并驱动被等待的 `Future` 推进直至产出 `T`。
除 `async fn` 外,还可以用 `async { ... }` 异步块在任意位置构造 `Future` 并在块内串联多个 `.await`。顶层驱动异步任务需交给执行器,常见入口包括 `#[tokio::main]`、`async_std::task::block_on` 或 `futures::executor::block_on`。当异步操作返回 `Result` 时,可直接写 `some_async_operation().await?`:先等待 `Future` 完成,再由 `?` 将 `Err` 向上传播。离线校验器已核对 `hello()` + `add(1, 2)` 组合及 `.await?` 对成功/错误桩的传播。
异步 Trait、任务派生、异步 I/O 与异步通道
Rust 支持在 `trait` 中直接声明 `async fn` 方法(Rust 1.75+ 已原生稳定静态派发的 `async fn in trait`;若需 `dyn Trait` 动态派发可借助 `async-trait` 宏)。在异步运行时上下文中,`#[tokio::main]` 宏负责搭建运行时,`tokio::spawn(async { ... })`(运行时提供的异步任务派生函数,与宏相配合)用于在后台并发调度新任务并返回一个可 `.await` 的 `JoinHandle`。
为避免阻塞事件循环,异步程序应选用运行时提供的异步 I/O 与同步原语(注意 `tokio::fs::File`、`AsyncReadExt` 与 `tokio::sync::mpsc::channel(32)` 来自第三方运行时 crate 而非 `std` 标准库):例如使用 `tokio::fs::File::open(...).await?` 配合 `read_to_string(...).await?` 异步读文件,或通过有界异步通道 `tx.send(...).await` / `rx.recv().await` 在并发任务间传递消息。综上,`async/await` 让开发者能够以接近同步代码的清晰结构编写高并发、内存安全的非阻塞程序。本站离线脚本已用 `asyncio.create_task`、容量 32 的 `asyncio.Queue` 与临时目录异步读文件复现并验证全套协作行为。
运行离线 Python 校验:Rust Future 惰性轮询、asyncio 协作任务、.await? 与容量 32 异步通道
"""Offline Rust semantic verifier for Chapter 29: Async/Await (Future lazy polling, asyncio tasks, .await?, async mpsc)."""
import asyncio
import json
from pathlib import Path
import tempfile
class PollCounterFuture:
"""Models a Rust Future returning Poll::Pending until polled `ticks` times, then Poll::Ready(value)."""
def __init__(self, ticks: int, value: int) -> None:
self.remaining = ticks
self.value = value
self.poll_count = 0
def poll(self) -> tuple[str, int | None]:
self.poll_count += 1
if self.remaining > 0:
self.remaining -= 1
return ("Pending", None)
return ("Ready", self.value)
async def async_task() -> int:
await asyncio.sleep(0)
return 42
async def execute_async_task(log: list[str]) -> int:
res = await async_task()
log.append(f"Async task result: {res}")
return res
async def hello() -> str:
return "Hello, world!"
async def add(a: int, b: int) -> int:
return a + b
async def mock_fetch_url(url: str) -> tuple[str, str]:
await asyncio.sleep(0)
if url.startswith("https://offline.local/posts/1"):
return ("Ok", '{"id": 1, "title": "offline-post"}')
return ("Err", f"unrecognized offline route: {url}")
async def async_error_propagation(url: str) -> tuple[str, str]:
status, payload = await mock_fetch_url(url)
if status == "Err":
return ("Err", payload)
return ("Ok", payload)
async def run_async_suite() -> list[dict]:
cases = []
# Case 1: Lazy Future polling (Pending -> Pending -> Ready) & async_task() -> 42
fut = PollCounterFuture(ticks=2, value=42)
polls = [fut.poll(), fut.poll(), fut.poll()]
log: list[str] = ["Start executing async task..."]
val = await execute_async_task(log)
log.append("Async task completed!")
actual_1 = {
"poll_trace": [list(p) for p in polls],
"task_value": val,
"execution_log": log,
}
expected_1 = {
"poll_trace": [["Pending", None], ["Pending", None], ["Ready", 42]],
"task_value": 42,
"execution_log": [
"Start executing async task...",
"Async task result: 42",
"Async task completed!",
],
}
cases.append(dict(
name="future_polling_and_async_task",
summary="Verify lazy Future Poll::Pending -> Poll::Ready state transitions and async_task() == 42",
expected=expected_1,
actual=actual_1,
passed=actual_1 == expected_1,
))
# Case 2: async fn, async block equivalent, and .await? error propagation
r1 = await hello()
r2 = await add(1, 2)
ok_fetch = await async_error_propagation("https://offline.local/posts/1")
err_fetch = await async_error_propagation("https://offline.local/missing")
actual_2 = {
"async_block_result": f"Result: {r1}, {r2}",
"fetch_ok": list(ok_fetch),
"fetch_err_propagated": err_fetch[0] == "Err",
}
expected_2 = {
"async_block_result": "Result: Hello, world!, 3",
"fetch_ok": ["Ok", '{"id": 1, "title": "offline-post"}'],
"fetch_err_propagated": True,
}
cases.append(dict(
name="async_block_and_await_question_mark",
summary="Verify async fn composition (hello + add) and .await? Ok/Err propagation using offline stub",
expected=expected_2,
actual=actual_2,
passed=actual_2 == expected_2,
))
# Case 3: Spawned async tasks, bounded async mpsc channel, and async-style local file read
ch: asyncio.Queue[str] = asyncio.Queue(maxsize=32)
async def producer() -> None:
await ch.put("Hello, world!")
child = asyncio.create_task(producer())
received = await ch.get()
await child
with tempfile.TemporaryDirectory() as tmp:
fp = Path(tmp) / "file.txt"
fp.write_text("async-io-content", encoding="utf-8")
contents = await asyncio.to_thread(fp.read_text, encoding="utf-8")
actual_3 = {
"mpsc_received": f"Received: {received}",
"async_file_contents": contents,
"channel_capacity": ch.maxsize,
}
expected_3 = {
"mpsc_received": "Received: Hello, world!",
"async_file_contents": "async-io-content",
"channel_capacity": 32,
}
cases.append(dict(
name="async_spawn_mpsc_and_file_io",
summary="Verify spawned async task sending over capacity-32 mpsc channel and non-blocking temp file read",
expected=expected_3,
actual=actual_3,
passed=actual_3 == expected_3,
))
return cases
def main() -> None:
payload = {
"version": "CPython 3.12.14 offline Rust semantic verifier (rustc absent)",
"cases": asyncio.run(run_async_suite()),
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对 Pending->Pending->Ready(42) 轮询轨迹、async_task 顺序日志、.await? 离线桩错误传播、容量 32 mpsc 通道及异步读临时文件。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:c1b96aa78af3463dbabc44c00c70205d8a02c3ac4e8932df01467128b7f844d2
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:d9e548872c68adaef0b301da5e9b11ab517bebe42b5acfb23cb87789c3f66183
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么仅调用一个 async fn 而不对其返回值执行 .await 或交给执行器,函数体内的代码根本不会运行?异步任务中为何不能随意使用 std::fs 同步文件读写?
展开参考解答
Rust 的 Future 是惰性的(lazy),调用 async fn 只是构造出未启动的状态机对象,必须经执行器 poll(通常经 .await 或 block_on 触发)才会推进执行;在异步工作线程中直接做长时间阻塞的 std::fs 或 std::thread::sleep 会卡住调度器线程,导致同一线程上的其他异步任务饿死。