SuperAPI AI 工具集

rust-impl-async-tokio

编程与开发

查看项目

更新于 10-15 22:18

技能介绍

用途:指导在 Rust 中使用 tokio 1.x(Rust 1.85+、edition 2024)实现异步运行时相关代码,包括启动运行时、派生与等待任务、用 select! 竞速、设置超时、安全取消以及用 JoinSet 做结构化并发。

主要能力:运行时选择(current_thread 与 multi_thread,含 #[tokio::main] 与 Builder 显式构建);阻塞代码处理(spawn_blocking、block_in_place、rayon,避免在 async 中调用 std::fs/std::net);任务派生与 JoinHandle、abort、分离语义;select! 的随机轮询、biased; 优先级、if 守卫与 else 分支;timeout/timeout_at 与取消安全;基于 drop 的取消语义与 CancellationToken;JoinSet 的 join_next、abort_all、shutdown、detach_all;task_local! 任务本地存储。

必要用法:Cargo.toml 需启用 macros 与 rt-multi-thread(或 rt)特性;#[tokio::main] 是 Runtime::new 加 block_on 的语法糖;不要在 async 中再建运行时,改用 Handle::current();跨 .await 持有 std::sync::Mutex 需谨慎,否则改用 tokio::sync::Mutex。

适用场景:服务器多核吞吐、单线程 !Send 数据、CPU 密集或同步 IO 的隔离执行、超时与优雅关闭、并行任务扇出与统一取消、请求级追踪上下文。

限制:abort 是协作式的,仅在下一个 .await 点生效,无法停止不 yield 的 CPU 密集代码;非取消安全的 future 不应直接放入 select! 或 timeout;JoinError 需区分 is_panic 与 is_cancelled,不应静默吞掉。具体 API 签名、示例与反模式见其 references 目录,资料未提供更多细节。