# pi-async-runtime
由外部线程(thread)推进的串行运行时(serial runtime)与单线程并发运行时(single-threaded concurrent runtime)。
## 目标、适用范围与支持条件
本库组合任务(Task)、队列(queue)、计时和默认执行器(executor),面向由所属线程(owner thread)推进异步业务的应用。应用可从本库或 `prelude` 导入常用公开接口(API)。
本库采用 Rust 2021,本文示例使用 Linux x86_64 和 `nightly-2026-07-19` 验证。Windows x64/MSVC 有既往验证。最低支持 Rust 版本(MSRV)、Android 和 WebAssembly(Wasm)尚未确认。本地计时从 `0.1.3` 起提供,使用该版本时依赖解析需要 `pi-async-runtime-core 0.1.3`。
## 使用前须了解的特性和术语
- **拥有者(owner)**是在所属线程(owner thread)推进原服务的完整运行时(runtime)对象。
- **共享句柄(shared handle)**指向同一个运行时(runtime)。可克隆(Clone)、跨线程提交和查询,推进业务仍由拥有者(owner)负责。
- **接纳(admission)**是执行器(executor)取得任务(Task)并承担后续推进的环节。串行与并发模式的区别在于上一项任务(Task)挂起期间怎样接纳新的外部任务。
## 公开特性(feature)及组合
| 特性(feature) | 默认 | 作用 |
| --- | --- | --- |
| `observe` | 关闭 | 转发执行器(executor)和运行时核心(runtime core)的观测能力,允许任务配置携带观测者。 |
`observe` 可独立启用。清单未声明互斥组合。默认定时来源由依赖库的 `cancel-timer` 提供。
## 能力、类型与接口(API)
### 接入和选择运行时
```toml
[dependencies]
pi-async-runtime = "0.1"
pi-clock-manual = "0.1"
```
已锁定旧版本的应用更新 `pi-async-runtime` 到 `0.1.3` 时,要同时更新锁文件(lockfile)中的 `pi-async-runtime-core` 到 `0.1.3`。用 `cargo tree -i pi-async-runtime-core` 可以核对实际解析版本。使用路径依赖(path dependency)时保留完整工作区(workspace),并准备 `pi-clock` 兄弟目录。应用直接依赖的各库也应使用同一份本地源码,其中 `pi-clock-manual` 须指向运行时所依赖的 `pi-clock/crates/manual`,确保使用同一个全局时钟(global clock)。
| 名称 | 行为 |
| --- | --- |
| `SerialRuntime` | 已接纳任务族尚未结束时暂停接纳下一普通外部批次;本地任务可继续交替推进。 |
| `ConcurrentRuntime` | 每轮积极尝试普通来源;已有任务挂起时仍可接纳其它任务。 |
| `Runtime` | `ConcurrentRuntime` 的默认类型别名。 |
两种实现都由一个所属线程(owner thread)执行。并发(concurrency)指多个异步计算轮流推进,CPU 并行(parallelism)需要由其它执行线程承担工作。应用负责创建推进线程(thread),输入输出驱动(I/O driver)由宿主另外提供。
串行运行时仍允许外部线程持续并发提交。暂停的是下一批普通任务的接纳,不是外部来源的接收。
#### 初始化时钟、派发任务(Task)并领取结果
```rust
use pi_async_runtime::{ConcurrentRuntime, RuntimeBlockOn, TaskDispatch};
// 应用入口负责安装全进程使用的同一个单调时钟。
pi_clock_manual::global::try_init().expect("初始化全局时钟");
let runtime = ConcurrentRuntime::new().expect("创建运行时");
let result = runtime.spawn(async { 6_u32 * 7 }).expect("提交任务");
assert_eq!(runtime.block_on(result).unwrap(), 42);
```
将类型换成 `SerialRuntime` 可运行同一个例子。应用线程在 `block_on` 中推进服务。若要先处理宿主自己的事件,完整拥有者(owner)也可按需调用 `run_once`。
### 常用入口与组合约束
```rust
use pi_async_runtime::{RuntimeCapabilities, RuntimeStatus};
fn runtime_is_open<R: RuntimeCapabilities>(runtime: &R) -> bool {
// 通用调用方只依赖标准能力。状态采样不保证后来提交仍可接收。
runtime.status() == RuntimeStatus::Open
}
```
这段代码展示通用调用所需的接口(API)约束。`RuntimeCapabilities` 重导出核心的 `Runtime` 特征(trait),具体类型(type)使用 `Runtime` 别名。只用部分能力的调用者可使用对应的特征(trait)约束。
| 需求 | 入口 |
| --- | --- |
| 普通派发 | `TaskDispatch::{create, submit, spawn}` 及配置版本。 |
| 本地快速派发 | `LocalTaskDispatch::{create_local, submit_local, spawn_local}`,静态关联入口。 |
| 空闲派发 | `IdleDispatch::{idle, idle_local, submit_idle}`。 |
| 定时派发 | `TimedTaskDispatch::{spawn_timing, spawn_timing_local}`。 |
| 计时等待 | `RuntimeTime::{timeout, timeout_on, sleep}`。 |
| 本地计时等待 | `RuntimeTime::{timeout_local, timeout_on_local, sleep_local}`。通过运行时类型调用,使用当前有效的本地定时任务队列。 |
| 普通交值等待 | 自由函数 `wait_one/wait_any/wait_all`。 |
| 带超时交值等待 | `RuntimeWait::{wait_one_timeout, wait_any_timeout, wait_all_timeout}`。 |
| 主动让出一次 | 自由异步函数 `yield_now`,需要实际等待它。 |
| 查询与关闭请求 | `RuntimeQuery` 与 `RuntimeControl`。 |
| 当前服务访问 | `RuntimeContext`;公共选择与本地操作权限分别核对。 |
| 当前任务信息 | `try_current_task_id/try_with_current_metadata`。 |
普通派发要求计算与输出 `Send + 'static`,不额外要求 `Sync/Unpin`。本地派发允许非 `Send` 计算,但需要当前有效的所属线程权限。`idle_local` 的内容仍要求 `Send`,不要求 `Sync`。
普通 `wait_one/wait_any/wait_all` 是自由函数(free function)。带超时的等待使用当前实例或显式传入的共享句柄(shared handle)。`RuntimeTime` 的三个 `*_local` 方法通过匹配的运行时类型调用,目标由当前有效本地访问决定。
### 构造、配置与推进
`new()` 使用默认配置;`with_options(RuntimeOptions)` 设置四组工作配置:普通来源、空闲来源、定时来源及执行器。`with_components` 支持静态组合时钟、策略和钩子,由参数推导具体类型,不必在常规调用处手写内部泛型链。
#### 全局时钟(global clock)如何与推进合用
1. **应用初始化一次。** 在构造运行时(runtime)或启动所属线程(owner thread)之前,调用 `pi_clock_manual::global::try_init()`。重复初始化会返回错误并保留已安装的时钟。库代码由宿主负责初始化,构造时用 `ManualClock::new()` 核对可用。
2. **运行时主动采样。** 默认 `ManualClock` 在需要当前时间时调用 `pi_clock_manual::global::try_refresh()`,从同一个单调时间轴取得时间。正常使用 `run`、`run_once` 或完整拥有者的 `block_on` 即可推进定时任务,应用无需再启动时钟刷新线程。业务直接使用 `global::try_now()` 可读到最近发布的时间样本。需要主动取样时调用 `try_refresh()`。
3. **使用同一时间轴。** 选配定时任务队列(timer task queue)时,构造回调应使用运行时传入的时钟(clock)和线程通知句柄(ThreadNotifier)。不要把系统墙钟、独立进程的时间或另一时间轴的结果混入。用指定的时长(Duration)安排任务,由对应计时来源计算截止时刻。
4. **分开管理生命周期(lifecycle)。** 关闭某个运行时仅结束原服务,进程的全局时钟仍可供其它运行时使用。若应用自行启用 `pi-clock-manual` 的可选自动刷新(auto-refresh),由启动它的宿主通过 `auto_refresh::try_stop_and_join()` 结清该线程。
在直接定制时钟时,用 `with_components` 接收实现 `ExecutorClock<Instant = GlobalManualInstant>` 的类型。所有副本须访问同一单调时间轴,`checked_add` 和 `remaining` 用给出的点计算。冻结的测试时间可显式推进以检查到期边界。生产计算应继续真实采样。
配置可以先独立准备,再交给所选的运行时(runtime)构造入口。
```rust
use std::num::NonZeroUsize;
use pi_async_runtime::RuntimeOptions;
let mut options = RuntimeOptions::default();
// 只调整普通来源的每步管理工作额度。
options.external_queue.cleanup_batch_size = NonZeroUsize::new(32).unwrap();
assert_eq!(options.external_queue.cleanup_batch_size.get(), 32);
```
#### 分别选择三类队列
两种单线程运行时(single-threaded runtime)均可用 `with_queues` 指定队列(queue)。每个缺项使用该运行时的默认队列。已有具象实例的配置随实例保留。构造入口按值接收选配。构造失败时,创建线程负责释放已移交的管理者和未调用的定时回调(callback),调用方收到原报告(Report)。`RuntimeOptions` 中对应的队列选项只用于未指定的来源。
此例直接依赖队列库(crate)和执行器(executor),分别移交外部及空闲来源,并在定时构造回调中用同源的时钟(clock)和通知(notification)准备定时来源。只需要选配其中一类时,保留相应的 `with_*` 调用即可。
```toml
[dependencies]
pi-async-runtime = "0.1"
pi-async-task-queue = { version = "0.1", features = ["cancel-timer"] }
pi-async-executor = "0.1"
pi-clock-manual = "0.1"
```
```rust
use pi_async_executor::{DefaultTimerDriver, ExecutorClock, ManualClock};
use pi_async_runtime::{
IdleDispatch, RuntimeBlockOn, RuntimeOptions, RuntimeQueues, SerialRuntime, TaskDispatch,
TimedTaskDispatch,
};
use pi_async_task_queue::{CancelTimerQueue, MpscIdleTaskQueue, MpscTaskQueue};
use std::time::Duration;
pi_clock_manual::global::try_init().unwrap();
let options = RuntimeOptions::default();
let external = MpscTaskQueue::new(options.external_queue).unwrap();
let idle = MpscIdleTaskQueue::new(options.idle_queue).unwrap();
let timer_options = options.timer;
let queues = RuntimeQueues::default()
.with_external(external)
.with_idle(idle)
.with_timer(move |id, clock: &ManualClock, notifier| {
// 用最终执行器的通知句柄构造来源,并交给同一服务的定时驱动。
let queue = CancelTimerQueue::new(clock.now()?, notifier.clone(), timer_options)?;
DefaultTimerDriver::from_queue(id, *clock, notifier, queue)
});
let runtime: SerialRuntime = SerialRuntime::with_queues(options, queues).unwrap();
let data = runtime.spawn(async { 42 }).unwrap();
let maintenance = runtime.idle(async { "清理结束" }).unwrap();
let timer = runtime.spawn_timing(async { "定时工作" }, Duration::ZERO).unwrap();
runtime.block_on(async {
assert_eq!(data.await.unwrap(), 42);
assert_eq!(maintenance.await.unwrap(), "清理结束");
assert_eq!(timer.await.unwrap(), "定时工作");
});
```
`with_idle` 接收选定的空闲任务队列(idle task queue)管理者。`with_timer` 的构造回调(callback)接收本次最终的运行时编号(RuntimeId)、时钟(clock)和线程通知句柄(ThreadNotifier),返回同源的定时设施。原已准备实例须先确认原通知配对、时间和接收状态。需要同时指定时钟(clock)、策略和钩子(hook)时使用 `with_components_and_queues`。内部任务队列(internal task queue)由原执行器(executor)创建,不配置。
选配后通过原运行时的派发(dispatch)入口提交,运行时会核对任务归属并安排通知(notification)。构造前保留的原队列共享句柄(shared handle)仍可按该队列的约定使用,直接提交者负责核实任务归属和通知责任。本地操作仍遵守原所属线程的权限。
### 由应用线程(thread)推进两种运行时
| 推动方式 | 作用与权限 |
| --- | --- |
| 完整对象的 `run_once(&mut self)` | 推进一次事件循环,返回 `TurnResult`。 |
| 完整对象的 `run(&mut self)` | 在原合法线程持续推进服务。 |
| 完整对象的 `block_on(&self, future)` | 排他推进原服务及调用方根计算,根计算完成后返回。 |
| 共享 `Handle` 的 `block_on` | 只推进调用线程上的根计算,不代替拥有者推进原服务。 |
完整运行时绑定原线程,不支持 `Send/Sync`;`Handle` 支持 `Clone + Send + Sync`,克隆不复制服务,也不延长本地管理所有权。
在负责推进的线程构造完整运行时。拿到共享句柄的其它线程可投递和请求关闭。已经在一个线程绑定了运行时后,要先结束并释放旧实例,才能在该线程绑定另一个。不要在正在轮询(poll)的本地任务内嵌套 `block_on`。非法嵌套、目标冲突或非法推进会在首次轮询根计算前恐慌(panic)。
串行任务等待自己产生的子任务时应使用有效的本地派发;若把子任务提交到被暂停接纳的普通外部来源再等待它,可能形成互相等待。
#### 自定义空闲、休眠策略(IdlePolicy)并持续运行
`IdlePolicy::is_idle` 影响是否尝试初次接纳空闲任务(idle task)。默认策略(DefaultIdlePolicy)在没有可立即推进的工作时允许空闲,纯挂起(Pending)及尚未接纳的空闲任务无需单独否决。可以附加业务条件,例如只在已接纳任务都结束时运行维护任务。两种运行时的普通外部接纳规则仍各自保持。
`IdlePolicy::sleep_duration` 提供本轮最长休眠建议。返回 `None` 或零时长表示继续检查。持续返回这个结果可能使空服务反复空转。执行器(executor)采用策略建议、`ExecutorOptions::max_sleep` 和定时来源最迟检查时刻中的最短限制,休眠前再查可推进工作、关闭状态和通知(notification)。`max_sleep` 可在 1 至 10 毫秒之间选择,默认 10 毫秒。
线程(thread)可由实际提交、唤醒(wake-up)、取消请求(cancellation request)和关闭请求(close request)提前唤醒,也会在有限等待结束后重查。休眠返回只说明应该重查,具体业务是否到期由同源时钟(clock)判断。策略(policy)在所属线程(owner thread)同步执行,应快速返回,不应阻塞等待同一运行时处理的工作。`ExecutorSnapshot` 是一次只读样本。只有确实需要时才调用会遍历登记项的 `waiting_for_wake_tasks` 与 `pending_cancel_tasks`。
下面是一个可独立运行的应用。额外直接依赖 `pi-async-executor = "0.1"` 以导入策略输入,并依赖 `pi_result = "0.2"` 以保留工作线程的错误报告(Report)。同一个应用分别运行两种模式。
```rust
use pi_async_executor::ExecutorSnapshot;
use pi_async_runtime::{
mode::RuntimeMode, CloseState, ConcurrentMode, ConfiguredRuntime,
DefaultIdlePolicy, IdleDispatch, IdlePolicy, ManualClock, NoHooks, RuntimeBlockOn,
RuntimeControl, RuntimeOptions, RuntimeQuery, RuntimeStatus, SerialMode, TaskDispatch,
TimedTaskDispatch,
};
use std::{sync::mpsc, thread, time::Duration};
struct MaintenancePolicy {
default: DefaultIdlePolicy,
recheck: Duration,
}
impl IdlePolicy for MaintenancePolicy {
fn is_idle(&mut self, state: &ExecutorSnapshot<'_>) -> bool {
// 挂起的原任务仍在途。本应用将维护任务留到这些原任务结束以后。
state.in_flight_tasks == 0 && self.default.is_idle(state)
}
fn sleep_duration(&mut self, state: &ExecutorSnapshot<'_>) -> Option<Duration> {
// 休眠与是否允许运行维护任务分别决定。
// 业务仍可能挂起,此时没有可推进工作也应允许有限休眠。
self.default.sleep_duration(state).map(|limit| limit.min(self.recheck))
}
}
fn serve<M: RuntimeMode>() -> pi_result::Result<()> {
let (ready, handles) = mpsc::channel();
let owner = thread::spawn(move || -> pi_result::Result<()> {
let mut options = RuntimeOptions::default();
options.executor.max_sleep = Duration::from_millis(5);
let policy = MaintenancePolicy {
default: DefaultIdlePolicy,
recheck: Duration::from_millis(2),
};
// 完整对象在实际推进它的线程构造和释放。
let mut runtime = ConfiguredRuntime::<M, _, _, _>::from_components(
ManualClock::new()?, policy, NoHooks, options,
)?;
if ready.send(runtime.handle()).is_err() {
return Ok(()); // 调用方已退出,原线程直接释放实例。
}
runtime.run()
});
let handle = match handles.recv() {
Ok(handle) => handle,
// 未取得句柄,回收线程并把构造阶段的原报告交回应用。
Err(_) => return owner.join().expect("所属线程未恐慌"),
};
let value = handle.spawn(async { 42_u32 }).unwrap();
let later = handle.spawn_timing(async { "到期" }, Duration::from_millis(2)).unwrap();
let maintenance = handle.idle(async { "维护结束" }).unwrap();
// 这里只推进调用线程上的等待。owner 中的 run 继续执行原任务。
handle.block_on(async {
assert_eq!(value.await.unwrap(), 42);
assert_eq!(later.await.unwrap(), "到期");
assert_eq!(maintenance.await.unwrap(), "维护结束");
});
handle.request_close();
owner.join().expect("所属线程未恐慌")?;
assert_eq!(handle.status(), RuntimeStatus::Closed);
assert_eq!(handle.close_state(), CloseState::Completed);
Ok(())
}
pi_clock_manual::global::try_init().unwrap();
serve::<SerialMode>().unwrap();
serve::<ConcurrentMode>().unwrap();
```
在服务中,所属线程(owner thread)应将构造和 `run` 返回的原错误(error)交给管理线程。关闭先请求停收,再由原线程继续推进清理,最后回收应用创建的线程。应用要等待所有工作完成时,应像示例一样先等待各自的结果句柄(result handle),再请求关闭。发布空闲任务成功仅说明已经排队。自定义策略可能一直不允许接纳,应按应用策略决定是否给这类等待设期限。
#### 将 `run_once` 接入宿主事件循环(event loop)
使用 `run_once` 时,应用拥有等待下一轮的调度责任。`immediate_work` 表示本轮结果要求尽快重查。`sleep_for` 是上限建议,返回后可能有新的工作。它不为宿主的事件通知自动接线。这个例子用应用自己的通道加 1 毫秒重查上限。宿主通道的发送方在投递和请求关闭之后通知。其它来源,例如异步计算(Future)的唤醒,仍由下一轮有界重查处理。
```rust
use pi_async_runtime::{
mode::RuntimeMode, CloseState, ConcurrentMode, ConfiguredRuntime, DefaultIdlePolicy,
ManualClock, NoHooks, RuntimeBlockOn, RuntimeControl, RuntimeQuery, SerialMode, TimedTaskDispatch,
};
use std::{sync::mpsc, thread, time::Duration};
fn run_turns<M: RuntimeMode>() {
let mut runtime = ConfiguredRuntime::<M, ManualClock, DefaultIdlePolicy, NoHooks>::new()
.expect("在本线程创建");
let handle = runtime.handle();
let (host_tx, host_rx) = mpsc::channel();
let producer = thread::spawn(move || {
let answer = handle.spawn_timing(async { 42 }, Duration::from_millis(2)).unwrap();
host_tx.send(()).expect("宿主接收通知");
let value = handle.block_on(answer).unwrap();
handle.request_close();
let _ = host_tx.send(()); // 宿主可能已经观察到关闭。
value
});
let max_host_wait = Duration::from_millis(1);
loop {
let turn = runtime.run_once().expect("推进或清理一轮");
if turn.service_closed {
break;
}
if turn.immediate_work {
continue;
}
let wait = turn.sleep_for.map_or(max_host_wait, |hint| hint.min(max_host_wait));
match host_rx.recv_timeout(wait) {
Ok(()) | Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => {
// 生产端已退出,原线程继续完成关闭清理。
runtime.request_close();
}
}
}
assert_eq!(producer.join().unwrap(), 42);
assert_eq!(runtime.close_state(), CloseState::Completed);
}
pi_clock_manual::global::try_init().unwrap();
run_turns::<SerialMode>();
run_turns::<ConcurrentMode>();
```
1 毫秒是这个宿主例子的重查上限,实际延迟还取决于操作系统调度和每轮业务耗时。生产应用应在每轮之间处理自己的事件,选择能满足业务延迟的等待上限。若线程只负责这个运行时,用 `run` 取得与原工作通知和定时来源配对的休眠行为。不要在已有推进范围内另启动一轮推进。
#### 观察两种模式怎样接纳后续任务
先推进到第一项任务挂起,再提交第二项。这样可以直接用一次普通来源的数量查询看出差别。若两项任务已经在同一批中交给执行器(executor),不能按本例推断它们的先后。
```rust
use pi_async_runtime::{
mode::RuntimeMode, wait_one, ConcurrentMode, ConfiguredRuntime, DefaultIdlePolicy,
ManualClock, NoHooks, RuntimeBlockOn, RuntimeQuery, SerialMode, TaskDispatch,
};
fn observe_admission<M: RuntimeMode>(remaining_external: usize) {
let mut runtime = ConfiguredRuntime::<M, ManualClock, DefaultIdlePolicy, NoHooks>::new()
.unwrap();
let (gate, release) = wait_one();
let first = runtime.spawn(async move {
gate.await.unwrap();
10
}).unwrap();
runtime.run_once().unwrap();
assert_eq!(runtime.in_flight_task_count(), 1);
let second = runtime.spawn(async { 20 }).unwrap();
runtime.run_once().unwrap();
// 此例只有一个提交方,因此样本能直接区分第二项是否还在普通来源。
assert_eq!(runtime.external_task_count(), remaining_external);
release.send(()).unwrap();
let total = runtime.block_on(async { first.await.unwrap() + second.await.unwrap() });
assert_eq!(total, 30);
}
pi_clock_manual::global::try_init().unwrap();
observe_admission::<SerialMode>(1);
observe_admission::<ConcurrentMode>(0);
```
### 计时、空闲与结果
正时长 `timeout` 在首次轮询才开始登记;`timeout_on` 同轮优先观察业务完成,业务完成后处理不再需要的计时等待。正超时支持至少1ms,也允许超过1s;`sleep` 的正时长范围为1ms至1s。
零超时等价于让出一次,不建立正时长登记,不能成功取消。`yield_now` 是惰性异步函数,只有被轮询才让出;它不承诺运行所有其它任务或等待外部通知。
#### 在运行时(runtime)中使用本地派发和本地计时
两种模式的本地调用都使用当前所属线程(owner thread)的有效访问。下面的串行运行时使用 `spawn_local` 推进子任务,子任务携带不可跨线程的 `Rc`。在根异步计算(root Future)中也能用 `timeout_on_local` 等待借用栈数据的异步计算(Future)。
```rust
use pi_async_runtime::{
IdleDispatch, LocalRuntimeAccessError, LocalTaskDispatch, RuntimeBlockOn, RuntimeTime,
SerialRuntime, TimedTaskDispatch,
};
use std::{rc::Rc, time::Duration};
pi_clock_manual::global::try_init().unwrap();
let runtime = SerialRuntime::new().unwrap();
assert!(matches!(
SerialRuntime::sleep_local(Duration::ZERO),
Err(LocalRuntimeAccessError::NoLocalRuntime),
));
let label = String::from("本地结果");
runtime.block_on(async {
let local = Rc::new(42_u32);
let result = SerialRuntime::spawn_local(async move {
// 正时长首次轮询时从当前本地定时来源登记。
SerialRuntime::sleep_local(Duration::from_millis(2)).unwrap().await.unwrap();
local
}).unwrap();
assert_eq!(*result.await.unwrap(), 42);
let answer = SerialRuntime::timeout_on_local(
async { label.as_str() },
Duration::from_millis(20),
).unwrap().await.unwrap();
assert_eq!(answer, "本地结果");
// timeout 等待指定时间并返回结果,零时长协作让出一次。
SerialRuntime::timeout_local(Duration::ZERO).unwrap().await.unwrap();
// 定时派发保留本地输出,空闲派发则使用可跨线程转交的结果。
let deferred = SerialRuntime::spawn_timing_local(
async { Rc::new(7_u32) },
Duration::from_millis(2),
).unwrap();
let maintenance = SerialRuntime::idle_local(async { "空闲维护" }).unwrap();
assert_eq!(*deferred.await.unwrap(), 7);
assert_eq!(maintenance.await.unwrap(), "空闲维护");
});
```
这三个入口先返回同一等待类型或本地访问错误。其后的 `.await` 仍可能返回计时错误(timer error)。`timeout_on_local` 同步拒绝会释放按值传入的计算。保持在原所属线程等待可确保正时长使用正确的本地登记。跨线程使用实例方法 `handle.timeout_on`、`handle.timeout` 或 `handle.sleep`。定时派发 `spawn_timing_local` 在调用时提交本地任务(local task),本地等待 `sleep_local` 要到首次轮询才登记。
#### 从带超时的等待(wait)连接到任务(Task)取消
```rust
use pi_async_runtime::{
CancellationOutcome, ConcurrentRuntime, RuntimeBlockOn, RuntimeWait, TaskDispatch,
TaskError, WaitTimeoutError,
};
use std::{future::pending, time::Duration};
pi_clock_manual::global::try_init().unwrap();
let runtime = ConcurrentRuntime::new().unwrap();
let work = runtime.spawn(pending::<()>()).unwrap();
let control = work.control_handle();
runtime.block_on(async {
// 设立一个待响应的请求。这个例子故意保留但不调用发送方。
let (reply, _sender) = runtime.wait_one_timeout::<u32>(Duration::from_millis(2));
assert!(matches!(reply.await, Err(WaitTimeoutError::Elapsed)));
// 超时只结束 reply。由另外一项受管任务发出取消并等待清理确认。
let cancel = runtime.spawn(async move { control.cancel_and_wait().await }).unwrap();
assert_eq!(cancel.await.unwrap(), CancellationOutcome::Cancelled);
assert!(matches!(work.await, Err(TaskError::Cancelled)));
});
```
`wait_any_timeout` 会保留竞争获胜及原值返还规则。`wait_all_timeout` 在成功时返回按登记顺序排列的逐项结果,超时时不返回部分结果。需要业务和计时之间只选择一个结果时,可以直接使用 `timeout_on`。
空闲任务只承诺提交,不保证被接纳或执行。初次接纳由外部空闲策略决定,接纳之后与普通任务一样轮询、挂起、唤醒和取消。`idle_local` 使用有效的当前本地访问定位共享空闲来源,其计算及输出仍须可跨线程转交。
派发成功不代表任务已完成;通过结果句柄等待完成。取消请求不等于原计算已经析构(drop),失败提交须处理返回的原值和对应句柄。
### 查询、关闭及成本
查询分别采样身份、运行状态、是否正在推进、最近空闲判断、关闭进度及七类数量,不承诺所有值对应同一个全局瞬间。
默认 `waiting_for_wake_count` 和 `pending_cancel_task_count` 只统计已接纳任务,按需扫描登记,成本为 O(n),n 为登记规模。其它查询沿各自约定取样。
上述两项查询与关闭并发时,已开始的查询可能在调用线程释放任务附加数据(task metadata)。启用 `observe` 且配置观测接收者(TaskObserver)时,同一次释放也可能报告 `TaskEvent::ReclaimStarted`。析构(drop)或该回调发生恐慌(panic)时,原载荷沿查询传播。已绑定任务的原异步计算(Future)仍由所属线程清理。
`request_close` 同步非阻塞,只登记请求并返回即时结果。共享句柄释放不自动关闭服务;完整拥有者负责撤销本地权限及合法清理。
`Closed` 表示服务不可用。`Closed/Completed` 表示规定清理成功确认,`Closed/Requested` 仍可能表示清理失败或尚未确认;重复关闭请求不能把失败变成成功。
#### 在同步范围内访问明确选择的运行时(runtime)
```rust
use pi_async_runtime::{
CurrentRuntimeAccessError, LocalRuntimeAccessError, RuntimeContext, RuntimeQuery, RuntimeTime,
SerialRuntime,
};
use std::time::Duration;
pi_clock_manual::global::try_init().unwrap();
let runtime = SerialRuntime::new().unwrap();
let id = runtime.id();
runtime.handle().enter(|| {
// 其它同步函数可在此范围借用公共选择。
assert_eq!(SerialRuntime::try_with_current(|current| current.id()).unwrap(), id);
// 尚未在所属线程建立有效的本地访问。
assert!(matches!(
SerialRuntime::sleep_local(Duration::ZERO),
Err(LocalRuntimeAccessError::NoLocalRuntime),
));
}).unwrap();
assert!(matches!(
SerialRuntime::try_current(),
Err(CurrentRuntimeAccessError::NoCurrentRuntime),
));
```
需要将环境带过异步等待点(await)时,直接把克隆的共享句柄(shared handle)传给异步计算(Future)。返回一个异步计算会结束 `enter` 的同步选择范围。创建或推进本地任务仍要求运行时真实具有相应的本地访问。
#### 分开创建与提交,并处理停收拒绝
```rust
use pi_async_runtime::{
CloseState, ExternalPushErrorKind, RuntimeControl, RuntimeQuery, SerialRuntime,
SubmitErrorKind, TaskConfig, TaskDispatch,
};
pi_clock_manual::global::try_init().unwrap();
let mut runtime = SerialRuntime::new().unwrap();
let (prepared, result) = runtime.create_with_config(async { 42_u32 }, TaskConfig::new(7_u32)).unwrap();
let id = result.id();
assert_eq!(*result.metadata(), 7);
runtime.request_close();
let (original, cause) = runtime.submit(prepared).unwrap_err().into_parts();
assert!(matches!(cause, SubmitErrorKind::External(ExternalPushErrorKind::Closed)));
assert_eq!(original.id(), id);
drop(original); // 应用明确放弃未提交任务,先结清自己仍持有的待提交值。
assert!(runtime.run_once().unwrap().service_closed);
assert_eq!(runtime.close_state(), CloseState::Completed);
```
如果提交因暂时占用失败,可按报错的原因保管原 `UnsubmittedTask` 并在同一目标合适的时机重试。需要重新创建到其它目标时,用业务自己的原输入重新建立任务。结果句柄的身份始终指向原任务(Task)。
许可证(License)为 `MIT OR Apache-2.0`。