pi-async-runtime 0.1.5

单线程串行及并发异步运行时的静态组合
Documentation

pi-async-runtime

由应用线程(thread)推进的串行运行时(serial runtime)、单线程并发运行时(single-threaded concurrent runtime)、单线程本地运行时(single-threaded local runtime)和单线程权重运行时(single-threaded weighted runtime)。

目标、适用范围与支持条件

本库组合任务(Task)、队列(queue)、计时和默认执行器(executor),面向由所属线程(owner thread)推进异步业务的应用。应用可从本库或 prelude 导入常用公开接口(API)。

本库采用 Rust 2021,本文示例使用 Linux x86_64 和 nightly-2026-07-19 验证。Windows x64/MSVC 有既往验证。LocalRuntime、SerialRuntime 和 ConcurrentRuntime 已在 Chromium 的 wasm32-unknown-unknown 目标验证。最低支持 Rust 版本(MSRV)及其它 WebAssembly(Wasm)宿主(host)尚未确认。浏览器(browser)的构造、推进和定时条件见专节。本地计时从 0.1.3 起提供,使用该版本时依赖解析需要 pi-async-runtime-core 0.1.3。

使用前须了解的特性和术语

  • **拥有者(owner)**是在所属线程(owner thread)推进原服务的完整运行时(runtime)对象。
  • **共享句柄(shared handle)**在 SerialRuntime、ConcurrentRuntime 和 WeightedRuntime 上指向同一个运行时(runtime)。可克隆(Clone)、跨线程提交和查询,推进业务仍由拥有者(owner)负责。LocalRuntime 的提交与推进都在所属线程(owner thread)。
  • **接纳(admission)**是执行器(executor)取得任务(Task)并承担后续推进的环节。串行与并发模式的区别在于上一项任务(Task)挂起期间怎样接纳新的外部任务。

公开特性(feature)及组合

特性(feature) 默认 作用
observe 关闭 转发执行器(executor)和运行时核心(runtime core)的观测能力,允许任务配置携带观测者。

observe 可独立启用。清单未声明互斥组合。默认定时来源由依赖库的 cancel-timer 提供。

能力、类型与接口(API)

接入和选择运行时

[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 每轮积极尝试普通来源;已有任务挂起时仍可接纳其它任务。
LocalRuntime 同一线程提交和消费,普通派发与同线程唤醒(wake-up)使用同一份队列。定时任务队列(timer task queue)和空闲任务队列(idle task queue)默认省略,可分别选配。
WeightedRuntime 多个线程可提交给同一个所属线程(owner thread)。支持串行队列(serial queue)和加权并行档位,使用默认定时和空闲任务队列。WebAssembly(Wasm)不提供此类型。
Runtime ConcurrentRuntime 的默认类型别名。

每份运行时(runtime)都由一个所属线程(owner thread)执行。并发(concurrency)指多个异步计算轮流推进,CPU 并行(parallelism)需要由其它执行线程承担工作。应用负责创建推进线程(thread),输入输出驱动(I/O driver)由宿主另外提供。

串行运行时仍允许外部线程持续并发提交。暂停的是下一批普通任务的接纳,不是外部来源的接收。

初始化时钟、派发任务(Task)并领取结果

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。

常用入口与组合约束

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 方法通过匹配的运行时类型调用,目标由当前有效本地访问决定。

构造、配置与推进

SerialRuntime、ConcurrentRuntime 和 LocalRuntime 的 new() 均使用各自默认配置。单线程权重运行时(single-threaded weighted runtime)使用 WeightedRuntime::new_weighted()。SerialRuntime 和 ConcurrentRuntime 的 with_options(RuntimeOptions) 设置普通来源、空闲来源、定时来源和执行器(executor)。其 with_components 支持静态组合时钟、策略和钩子,由参数推导具体类型。LocalRuntime::with_options(ExecutorOptions) 调整执行器(executor)的工作额度,构造无需全局时钟(global clock)。需要定时或空闲派发时,用 LocalRuntime::with_queues 并选择相应队列。

全局时钟(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 推进定时任务。浏览器(browser)由回调(callback)调用 run_once。应用无需启动时钟刷新线程。业务直接使用 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)构造入口。

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)。每个缺项使用该运行时的默认队列。独立 SerialRuntime 的普通来源须为 MpscTaskQueue,与内部 TaskQueue 固定配对。传入其它可静态识别的管理者类型会在使用时钟或定时回调之前返回 InvalidInput。带非静态借用的外部管理者无法满足串行构造的类型约束。ConcurrentRuntime 可选择满足外部任务队列合同的具体管理者。已有具象实例的配置随实例保留。构造入口按值接收选配。构造失败时,创建线程负责释放已移交的管理者和未调用的定时回调(callback),调用方收到原报告(Report)。RuntimeOptions 中对应的队列选项只用于未指定的来源。

此例直接依赖队列库(crate)和执行器(executor),分别移交外部及空闲来源,并在定时构造回调中用同源的时钟(clock)和通知(notification)准备定时来源。只需要选配其中一类时,保留相应的 with_* 调用即可。

[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"
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)仍可按该队列的约定使用,直接提交者负责核实任务归属和通知责任。本地操作仍遵守原所属线程的权限。

按实例省略定时或空闲任务队列

RuntimeQueues::default() 仍选择原来的默认组合。使用 .without_timer() 或 .without_idle() 显式省略各自的队列,两个方法可以连用。两种单线程运行时(single-threaded runtime)均可选这四组。普通派发、查询、推进和关闭(close)在全部组合可用。

构造选择 还可以使用的接口
原默认组合 RuntimeTime、RuntimeWait、TimedTaskDispatch、IdleDispatch
.without_idle() 定时、带超时等待、定时派发,包括 *_local
.without_timer() idle 和 idle_local
两项连用 普通 wait_one、wait_any、wait_all 和普通派发

普通等待(wait)由业务创建,四种组合都可推进。RuntimeTime 及 RuntimeWait 所含的带超时等待需要定时任务队列(timer task queue)。如果构造时省略该队列,相应实例及本地关联方法没有实现,编译器会指出缺少定时能力。IdleDispatch 同样要求真实空闲队列。RuntimeCapabilities 和 RuntimeContext 是完整运行时的接口,省略任一项后仍可按上表使用单项接口。计数查询对省略的来源返回零。

下面使用默认外部任务队列(external task queue)和内部任务队列(internal task queue)。该实例既不需要全局时钟(global clock),也可执行普通任务并主动关闭。

use pi_async_runtime::{
    CloseState, ConcurrentRuntime, RuntimeBlockOn, RuntimeControl, RuntimeOptions,
    RuntimeQuery, RuntimeQueues, TaskDispatch,
};

let mut runtime = ConcurrentRuntime::with_queues(
    RuntimeOptions::default(),
    RuntimeQueues::default().without_timer().without_idle(),
).unwrap();
let result = runtime.spawn(async { 21 * 2 }).unwrap();
assert_eq!(runtime.block_on(result).unwrap(), 42);
assert_eq!(runtime.timer_registration_count(), 0);
assert_eq!(runtime.idle_task_count(), 0);
runtime.request_close();
assert!(runtime.run_once().unwrap().service_closed);
assert_eq!(runtime.close_state(), CloseState::Completed);

省略定时时,Rust 会拒绝计时方法。

use pi_async_runtime::{SerialRuntime, RuntimeOptions, RuntimeQueues, RuntimeTime};
use std::time::Duration;
let runtime = SerialRuntime::with_queues(RuntimeOptions::default(), RuntimeQueues::default().without_timer()).unwrap();
let _ = runtime.timeout(Duration::from_secs(1));

省略空闲队列时,Rust 会拒绝空闲派发。

use pi_async_runtime::{ConcurrentRuntime, IdleDispatch, RuntimeOptions, RuntimeQueues};
let runtime = ConcurrentRuntime::with_queues(RuntimeOptions::default(), RuntimeQueues::default().without_idle()).unwrap();
let _ = runtime.idle(async {});

选择内部任务队列(internal task queue)

ConcurrentRuntime 支持 RuntimeQueues::with_internal(queue) 按值移交合法的现成实例,或者 .with_internal_factory(|context| ...) 在所属域(owner domain)建立后再取得队列。现成实例须开放且为空,如果有预绑定的所属域,必须匹配执行器(executor)这次建立的域。内部队列由该执行器独占,不能通过克隆(Clone)使两个运行时持有同一实际内部队列。定时及空闲任务队列(idle task queue)仍可独立选配。

独立 SerialRuntime 固定使用 MpscTaskQueue + TaskQueue。传入其它可静态识别的内外部管理者类型会在定时及内部队列构造回调(callback)前返回 InvalidInput。如果使用回调选择同型队列,仍要通过开放、空和原所属域检查。

下面用一份自定义队列管理者保管原 TaskQueue,从本次创建的所属域取得实例。示例保留定时及空闲默认值,展示从同一权限提交本地任务、在本地计时,并等待原结果。普通并发生产者仍通过运行时共享句柄(shared handle)提交给对应的外部任务队列。

use pi_async_runtime::{
    ConcurrentRuntime, LocalTaskDispatch, RuntimeBlockOn, RuntimeOptions, RuntimeQueues, RuntimeTime,
};
use pi_async_task::{definitions::TaskOwnerId, Runnable};
use pi_async_task_queue::{InternalTaskQueue, QueueCleanupProgress, QueuePushError, TaskQueue};
use std::time::Duration;

// 定制队列的例子沿用原任务收发、数量和关闭语义。
struct Ready(TaskQueue);
impl InternalTaskQueue for Ready {
    fn try_push_internal_front(&mut self, task: Runnable) -> Result<(), QueuePushError> {
        self.0.try_push_internal_front(task)
    }
    fn try_push_internal_back(&mut self, task: Runnable) -> Result<(), QueuePushError> {
        self.0.try_push_internal_back(task)
    }
    fn pop_internal_front(&mut self) -> Option<Runnable> { self.0.pop_internal_front() }
    fn internal_len(&self) -> usize { self.0.internal_len() }
    fn internal_owner_id(&self) -> Option<TaskOwnerId> { self.0.internal_owner_id() }
    fn is_internal_closed(&self) -> bool { self.0.is_internal_closed() }
    fn clear_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
        self.0.clear_internal()
    }
    fn close_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
        self.0.close_internal()
    }
}

fn run_local<R: RuntimeBlockOn + LocalTaskDispatch + RuntimeTime>(runtime: &R) {
    runtime.block_on(async {
        // R 是实际返回的运行时类型,带该次选配。不要用另一个默认别名查当前本地权限。
        let output = R::spawn_local(async { 42 }).unwrap();
        R::sleep_local(Duration::from_millis(1)).unwrap().await.unwrap();
        assert_eq!(output.await.unwrap(), 42);
    });
}
pi_clock_manual::global::try_init().unwrap();
let options = RuntimeOptions::default();
let queues = RuntimeQueues::default().with_internal_factory(|context| Ok(Ready(context.task_queue())));
let instance = ConcurrentRuntime::with_queues(options, queues).unwrap();
run_local(&instance);

示例额外直接依赖 pi-async-task = "0.1" 和 pi_result = "0.2"。用其它具象队列时,保留原合法任务(Task)、精确数量和关闭(close)语义,确保已经接纳任务重新入队可成功。构造时选择自定义内部任务队列,高层运行时仍从原执行器兑现这些责任。自定义定时驱动既要使用本次回调给出的原身份和同一时钟,也要支持本次实际内部队列组合的本地提交;默认定时驱动自动匹配。

升级已有应用时,常用别名和交给 Rust 推导的构造继续可用。如果旧代码在选配构造上手写整组泛型参数(generic parameter),可删掉显式参数,让 Rust 根据队列值推导。如需标注 RuntimeQueues,默认定时构造应使用类型的默认参数,不再把它写成原回调的函数指针(function pointer)。

按任务生产者所在的线程选择队列

使用场景 当前构造及提交方式
使用默认配置 SerialRuntime::new() 或 ConcurrentRuntime::new() 绑定默认队列。普通 spawn 经外部任务队列(external task queue)提交。
只替换一类队列 通过 RuntimeQueues 的 with_external、with_internal 或 with_internal_factory、with_timer、with_idle 选择,其余未指定项使用默认队列。
生产与消费在所属线程(owner thread) 用 LocalRuntime 让普通提交、本地派发和同线程唤醒共用一份 TaskQueue。定时与空闲派发通过同一运行时(runtime)的构造选配。
多个线程提交,一个线程消费 在所属线程创建运行时(runtime),把运行时的共享句柄(shared handle)交给生产者。独立 SerialRuntime 使用 MpscTaskQueue;ConcurrentRuntime 可选其他实现了 ExternalQueueManager 的外部任务队列。

同一个线程生产和消费

如果工作只由所属线程创建和执行,可以用本地派发(local dispatch)跳过普通外部队列的交接。直接持有 Rc 的任务(Task)也适用。先通过完整运行时的 block_on 进入有效的本地范围。

use pi_async_runtime::{LocalTaskDispatch, RuntimeBlockOn, RuntimeQuery, SerialRuntime};
use std::rc::Rc;

pi_clock_manual::global::try_init().unwrap();
let runtime = SerialRuntime::new().unwrap();
runtime.block_on(async {
    // 任务的生产者和消费者都在当前所属线程(owner thread)。
    let input = Rc::new(40_u32);
    let answer = SerialRuntime::spawn_local(async move { *input + 2 }).unwrap();
    // 本地派发直接提交给内部任务队列(internal task queue)。
    assert_eq!(runtime.external_task_count(), 0);
    assert_eq!(answer.await.unwrap(), 42);
});

将类型换成 ConcurrentRuntime 可以使用相同的本地入口。当前构造仍为普通派发保留外部来源,TaskQueue 由执行器(executor)绑定为内部任务队列。若应用的生产者和消费者始终在同一线程,可使用下节的 LocalRuntime。

单线程本地运行时(single-threaded local runtime)

LocalRuntime::new() 在当前所属线程创建服务。用 TaskDispatch::spawn 即可在第一次推进之前提交。 普通提交和同线程唤醒(wake-up)都在同一份 TaskQueue 的队尾追加,执行器从队首取出。 任务 A 挂起时提交 B,再唤醒 A,B 会排在 A 本次运行前面。任务自己的先后依赖仍由应用等待结果。 跨线程唤醒已有任务仍可用,提交和推进权限留在所属线程(owner thread)。 LocalRuntime::new() 和 with_options() 默认省略定时任务队列(timer task queue)与空闲任务队列(idle task queue),无需安装全局时钟(global clock)。 普通 wait_one、wait_any、wait_all 和结果句柄的异步等待仍可用。

use pi_async_runtime::{CloseState, LocalRuntime, RuntimeControl, RuntimeQuery, TaskDispatch};

let mut runtime = LocalRuntime::new().unwrap();
let result = runtime.spawn(async { 6_u32 * 7 }).unwrap();

// 普通提交还没有开始运行。同一个线程推进一轮并取得结果。
assert_eq!(runtime.external_task_count(), 1);
assert_eq!(runtime.run_once().unwrap().runs, 1);
assert_eq!(runtime.external_task_count(), 0);

// 此例在原生平台同步取得已就绪的结果。异步宿主也可 await 该结果。
#[cfg(not(target_family = "wasm"))]
{
    use pi_async_runtime::RuntimeBlockOn;
    assert_eq!(runtime.block_on(result).unwrap(), 42);
}
runtime.request_close();
assert!(runtime.run_once().unwrap().service_closed);
assert_eq!(runtime.close_state(), CloseState::Completed);

同一线程内,如果任务需要持有 Rc 等不可跨线程对象,请在已有原运行时本地范围通过 LocalRuntime::spawn_local 创建。普通 spawn 仍使用 TaskDispatch 的 Send 类型约束。

# #[cfg(not(target_family = "wasm"))] {
use pi_async_runtime::{LocalRuntime, LocalTaskDispatch, RuntimeBlockOn};
use std::rc::Rc;

let runtime = LocalRuntime::new().unwrap();
let output = runtime.block_on(async {
    let value = Rc::new(40_u32);
    let work = LocalRuntime::spawn_local(async move { *value + 2 }).unwrap();
    work.await.unwrap()
});
assert_eq!(output, 42);
# }

在浏览器(browser)中使用相同的本地提交方式,推进交由应用的浏览器回调。完整构建和使用步骤见Wasm32 浏览器示例。

为 LocalRuntime 选配定时和空闲任务队列

从 LocalRuntimeQueues::default() 开始,按需添加 .with_default_timer() 或 .with_idle(queue),也可同时添加。仅选配空闲任务队列(idle task queue)时仍无需安装全局时钟(global clock)。启用定时时,在构造前安装全局时钟(global clock)。构造结果的具体类型由配置推导,运行时(runtime)自身的提交和推进仍由创建它的线程负责。

选择 可用接口
省略两项 普通 spawn、spawn_local、wait_one、wait_any 和 wait_all。
只选定时 增加 timeout、timeout_on、sleep 及对应的 *_local 关联方法,可用带超时的等待与定时派发(timed dispatch)。
只选空闲 增加 idle 和 idle_local。
两项都选 同时提供上述接口。

原生应用可用以下方式组合超时(timeout)、空闲派发(idle dispatch)与结果领取。空闲任务提交后也需要推进。下例由 block_on 在所属线程(owner thread)推进。

# #[cfg(not(target_family = "wasm"))]
# fn main() {
use pi_async_runtime::{
    ExecutorOptions, IdleDispatch, LocalRuntime, LocalRuntimeQueues, RuntimeBlockOn, RuntimeTime,
};
use pi_async_task_queue::MpscIdleTaskQueue;
use std::{future::pending, time::Duration};

// 应用启动时安装一次时钟(clock)。
pi_clock_manual::global::try_init().unwrap();
let idle_queue = MpscIdleTaskQueue::new(Default::default()).unwrap();
let queues = LocalRuntimeQueues::default()
    .with_default_timer()
    .with_idle(idle_queue);
let runtime = LocalRuntime::with_queues(ExecutorOptions::default(), queues).unwrap();

let idle_result = runtime.idle(async { 42_u32 }).unwrap();
assert_eq!(runtime.block_on(idle_result).unwrap(), 42);
let deadline = runtime.timeout_on(pending::<()>(), Duration::from_millis(2));
assert!(matches!(
    runtime.block_on(deadline),
    Err(pi_async_runtime::TimeoutError::Elapsed),
));
# }
# #[cfg(target_family = "wasm")]
# fn main() {}

若需指定定时任务队列(timer task queue)或调整默认定时驱动(timer driver)的选项,使用 .with_timer(|id, clock, notifier| …) 构造驱动。回调(callback)只在运行时(runtime)通过前置检查后执行一次,接收本实例的身份、时钟和线程通知句柄(ThreadNotifier)。idle_local 和计时的 *_local 关联方法使用构造返回的实际类型,例如在 R: RuntimeTime 的函数中调用 R::sleep_local。调用须位于该实例的有效本地范围内。浏览器示例展示了这种用法。

若移交空闲任务队列(idle task queue)前通过 IdleQueueManager::handle 取得了它的共享句柄(shared handle),该句柄继续按原队列的提交与关闭约定使用。宿主(host)依事件安排推进时,也要在队列接收此类提交后安排一轮 run_once。

多个线程提交,一个所属线程消费

下面只替换普通外部来源,定时任务队列(timer task queue)和空闲任务队列(idle task queue)使用默认值。两个线程分别通过指向同一运行时的共享句柄提交,接纳(admission)与执行均归创建运行时的线程。示例先收集结果句柄(result handle),再在所属线程推进。需要边提交边推进时,见由应用线程持续推进。

use pi_async_runtime::{RuntimeBlockOn, RuntimeOptions, RuntimeQueues, SerialRuntime, TaskDispatch};
use pi_async_task_queue::MpscTaskQueue;
use std::thread;

pi_clock_manual::global::try_init().unwrap();
let options = RuntimeOptions::default();
let external = MpscTaskQueue::new(options.external_queue).unwrap();
let queues = RuntimeQueues::default().with_external(external);
let runtime = SerialRuntime::with_queues(options, queues).unwrap();
let consumer = thread::current().id();

let (first, second) = thread::scope(|scope| {
    let first_handle = runtime.handle();
    let second_handle = runtime.handle();
    // 两个生产者分别取得同一运行时的提交能力。
    let first = scope.spawn(move || {
        first_handle.spawn(async { thread::current().id() }).unwrap()
    });
    let second = scope.spawn(move || {
        second_handle.spawn(async { thread::current().id() }).unwrap()
    });
    (first.join().unwrap(), second.join().unwrap())
});

runtime.block_on(async {
    assert_eq!(first.await.unwrap(), consumer);
    assert_eq!(second.await.unwrap(), consumer);
});

这两个任务来自普通多生产者单消费者(MPSC)队列。若分别使用串行运行时(serial runtime)和单线程并发运行时(single-threaded concurrent runtime),生产者的提交方式相同,上一项任务挂起时的接纳规则随运行时模式而定。

串行队列与加权并行档位

WeightedRuntime 固定使用 WeightedSerialParQueue 和 TaskQueue,且默认提供定时任务队列(timer task queue)和空闲任务队列(idle task queue)。先初始化全局时钟(global clock),再在消费线程上创建。生产线程通过共享句柄(shared handle)提交。普通 spawn 使用 TaskWeight::Middle。要指定串行队列或不同并行档位时,使用 spawn_with_queue。

A 开始后可以继续提交同组的 B。A 挂起时,所属线程(owner thread)仍能推进其它组或并行任务。A 的原异步计算(Future)完成析构(drop)后才能取出 B,应用可以继续保留 A 的结果句柄(result handle)。并行权重影响取出机会,相同或不同行为的任务都没有按权重完成的保证。

# #[cfg(not(target_arch = "wasm32"))]
# fn main() {
use pi_async_runtime::{
    wait_one, CloseState, QueueSelection, RuntimeBlockOn, RuntimeControl, RuntimeQuery,
    RuntimeStatus, SerialQueueIndex, TaskWeight, WeightedRuntime,
};
use std::thread;

pi_clock_manual::global::try_init().unwrap();
let mut runtime = WeightedRuntime::new_weighted().unwrap();
let owner = thread::current().id();
let group = QueueSelection::Serial(SerialQueueIndex::new(0).unwrap());
let (may_finish, release) = wait_one();

let (first, next, parallel) = thread::scope(|scope| {
    let serial_sender = runtime.handle();
    let parallel_sender = runtime.handle();
    let serial = scope.spawn(move || {
        let first = serial_sender.spawn_with_queue(async move {
            assert_eq!(thread::current().id(), owner);
            may_finish.await.unwrap();
            20
        }, group).unwrap();
        let next = serial_sender.spawn_with_queue(async move {
            assert_eq!(thread::current().id(), owner);
            22
        }, group).unwrap();
        (first, next)
    });
    let parallel = scope.spawn(move || {
        parallel_sender.spawn_with_queue(async move {
            assert_eq!(thread::current().id(), owner);
            11
        }, QueueSelection::Parallel(TaskWeight::High)).unwrap()
    });
    let (first, next) = serial.join().unwrap();
    (first, next, parallel.join().unwrap())
});

// 同组首项仍在等待,所属线程可以执行并行项。
assert_eq!(runtime.block_on(parallel).unwrap(), 11);
release.send(()).unwrap();
// 保留首项结果句柄,仍能取得同组后项。
assert_eq!(runtime.block_on(next).unwrap(), 22);
assert_eq!(runtime.block_on(first).unwrap(), 20);

runtime.request_close();
let report = runtime.run_once().err().expect("上游原生池分配保留到进程退出");
assert_eq!(*report.current_context(), pi_result::ErrorKind::Unsupported);
assert!(matches!(runtime.status(), RuntimeStatus::Closed));
assert!(matches!(runtime.close_state(), CloseState::Requested));
# }
# #[cfg(target_arch = "wasm32")] fn main() {}

使用上面的关闭示例时,应用还需直接依赖 pi_result = "0.2" 来匹配错误分类。关闭永久停收,已接收的任务按实际清理;最终报告指出上游分配无法释放。每个权重队列都保留一份这类分配到进程退出。适合复用已经构造的运行时。取出可能等待本次遇到的在途原生发布或原生重试。业务需要严格限定单轮返回时间时,请选用具有相应进展保证(progress guarantee)的来源。

只替换并发运行时的外部任务队列

已有 ConcurrentRuntime 配置可以按值接收同一实现。下面使用默认内部、定时和空闲队列(queue);仍可在构造时按照前文分别选配。固定组合的 SerialRuntime 会明确拒绝 WeightedSerialParQueue。

# #[cfg(not(target_arch = "wasm32"))]
# fn main() {
use pi_async_runtime::{
    ConcurrentRuntime, QueueSelection, RuntimeBlockOn, RuntimeOptions, RuntimeQueues, TaskWeight,
    WeightedSerialParQueue,
};

pi_clock_manual::global::try_init().unwrap();
let queues = RuntimeQueues::default().with_external(WeightedSerialParQueue::new());
let runtime = ConcurrentRuntime::with_queues(RuntimeOptions::default(), queues).unwrap();
let result = runtime.spawn_with_queue(async { 42 }, QueueSelection::Parallel(TaskWeight::Low)).unwrap();
assert_eq!(runtime.block_on(result).unwrap(), 42);
# }
# #[cfg(target_arch = "wasm32")] fn main() {}

队列管理者、共享句柄与不允许的构造

RuntimeQueues::with_external 按值接收管理者(owner)。克隆(Clone)访问句柄只产生同一队列的另一份访问。把该句柄用作管理者时会被编译器拒绝。

use pi_async_runtime::RuntimeQueues;
use pi_async_task_queue::{ExternalQueueManager, MpscQueueOptions, MpscTaskQueue};

let external = MpscTaskQueue::new(MpscQueueOptions::default()).unwrap();
let access = external.handle();
let _ = RuntimeQueues::default().with_external(access);

下面给外部管理者加一个包装,即使共享句柄(shared handle)类型保持相同,独立 SerialRuntime 也会拒绝该组合。这里保留默认定时选项,可以看到拒绝发生在检查全局时钟(global clock)之前。复制此例到应用时,还需直接依赖 pi_result = "0.2"。

use pi_async_runtime::{RuntimeOptions, RuntimeQueues, SerialRuntime};
use pi_async_task_queue::{
    ExternalQueueManager, MpscTaskQueue, MpscTaskQueueHandle, QueueCleanupProgress,
};

struct Wrapped(MpscTaskQueue);
impl ExternalQueueManager for Wrapped {
    type Handle = MpscTaskQueueHandle;
    fn handle(&self) -> Self::Handle { self.0.handle() }
    fn clear(&mut self) -> pi_result::Result<QueueCleanupProgress> { self.0.clear() }
    fn close(&mut self) -> pi_result::Result<QueueCleanupProgress> { self.0.close() }
}
let options = RuntimeOptions::default();
let wrapped = Wrapped(MpscTaskQueue::new(options.external_queue).unwrap());
let result = SerialRuntime::with_queues(options, RuntimeQueues::default().with_external(wrapped));
assert_eq!(*result.err().unwrap().current_context(), pi_result::ErrorKind::InvalidInput);

给不同的运行时分别构造各自的队列实例(instance)。共享句柄(shared handle)应交给同一运行时的生产者。释放任意一个访问句柄只结束本次持有。需要结束服务时,通过原运行时的关闭(close)入口处理。定时或空闲选配缺项会使用默认来源,也可在构造时显式省略。

由应用线程(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)。同一个应用分别运行两种模式。

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)的唤醒,仍由下一轮有界重查处理。

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),不能按本例推断它们的先后。

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);

在 Wasm32 浏览器(browser)中构建和推进

本节适用于浏览器(browser)的 wasm32-unknown-unknown。示例在一个线程(thread)上推进运行时(runtime),已在 Chromium 验证。其它 WebAssembly(Wasm)宿主(host)、共享内存与多线程配置的支持范围需分别验证。

运行时(runtime) 浏览器(browser)中的构造 可以使用的等待(wait)
单线程本地运行时(single-threaded local runtime)LocalRuntime LocalRuntime::new() 无需安装时钟(clock)。要启用定时或空闲派发,用 LocalRuntime::with_queues 分别选配。两种构造都由同一线程提交、推进和取结果。 普通 wait_one、wait_any、wait_all 与结果句柄(result handle)。启用定时后还可计时、带时限等待和定时派发(timed dispatch)。
串行运行时(serial runtime)SerialRuntime、单线程并发运行时(single-threaded concurrent runtime)ConcurrentRuntime(也就是 Runtime) 使用默认定时任务队列(timer task queue)时先安装浏览器时钟。也可通过 RuntimeQueues::without_timer() 省略定时并直接构造。 普通等待均可用。绑定定时任务队列后,可以用计时、带超时的等待和定时派发(timed dispatch)。空闲派发(idle dispatch)要求绑定空闲任务队列(idle task queue)。
单线程权重运行时(single-threaded weighted runtime)WeightedRuntime wasm32 目标不导出该类型。 浏览器中需要定时与并发接纳(admission)时可使用有定时的 ConcurrentRuntime 或 LocalRuntime。
阻塞式运行时(blocking runtime)BlockingRuntime 需要原生成员线程,不支持这个浏览器目标。 浏览器中选择上方的单线程运行时。

① 准备浏览器应用

下例由 wasm-bindgen 暴露异步入口给 JavaScript。准备一个独立应用目录,创建 Cargo.toml、src/lib.rs 和 web/index.html。示例采用当前源码,pi-async-rt、pi-clock 和清单(manifest)引用的 pi_task_pool 是相邻目录。按实际目录改路径,Wasm 构建不会编译原生的 pi_task_pool。使用已发布库时应核对所用版本已提供这里的构造入口,并确保应用和运行时使用同一来源的 pi-clock-manual。

[package]
name = "browser-runtime-example"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[features]
default = ["browser-clock"]
browser-clock = ["dep:pi-clock-manual", "pi-clock-manual/browser"]

[dependencies]
pi-async-runtime = { path = "../pi-async-rt/crates/runtime" }
pi-async-task-queue = { path = "../pi-async-rt/crates/task-queue" }
pi-clock-manual = { path = "../pi-clock/crates/manual", default-features = false, optional = true }
js-sys = "0.3"
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"

browser-clock 是示例应用的特性(feature)。它打开同一份 pi-clock-manual 的 browser 特性,供默认定时使用。运行时(runtime)的 observe 与这项选择无关。用 --no-default-features 构建此应用时,只运行本地和省略定时的示例。

② 从同线程交值与单轮推进开始

把这段保存为 src/lib.rs。先提交,再从浏览器(browser)回调(callback)逐轮调用 run_once。每轮结束后,把控制权交还浏览器。请从宿主(host)推进,避免从任务(Task)内部重入 run_once。在 Wasm32 上,LocalRuntime 没有 run 和 RuntimeBlockOn。另外两种运行时(runtime)保留这些接口,调用需要宿主支持线程休眠,浏览器中使用 run_once。

  • immediate_work 为真时可尽快安排下一次回调(callback)。否则可用 sleep_for 估计何时重查,或用应用已有的事件(event)安排下一轮。sleep_for 是策略给出的休眠建议,定时截止时间另有独立判断。下例还把建议的重查间隔限制在 16 毫秒内,便于处理应用无法直接订阅的事件引发的任务唤醒(wake-up)。浏览器(browser)决定实际的回调时间,后台页面可能推迟回调。
  • spawn 提交后取得结果句柄(result handle)。异步等待它只取结果,推动任务仍是应用的职责。下例在每轮后检查一次,并在同线程使用普通等待(wait)承接浏览器的输入。需要携带 Rc 时,进入已经活动的本地范围后调用 spawn_local。普通 spawn 的 Send 约束在浏览器也适用。
  • 应用结束时先在所属线程(owner thread)调用 request_close,再用 run_once 确认 service_closed 和 CloseState::Completed。应用不再安排后续推进。
use pi_async_runtime::{
    wait_all, wait_any, wait_one, CloseState, ConcurrentRuntime, LocalRuntime, RuntimeControl,
    RuntimeOptions, RuntimeQuery, RuntimeQueues, SerialRuntime, TaskDispatch, TaskError,
    TurnResult,
};
use std::{
    fmt::Debug,
    future::{poll_fn, Future},
    pin::pin,
    task::Poll,
};
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;

#[wasm_bindgen(inline_js = "
export function nextTurn(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
")]
extern "C" {
    #[wasm_bindgen(js_name = nextTurn)]
    fn next_turn(ms: u32) -> js_sys::Promise;
}

fn js_error(error: impl Debug) -> JsValue {
    JsValue::from_str(&format!("{error:?}"))
}

async fn yield_to_browser(ms: u32) -> Result<(), JsValue> {
    JsFuture::from(next_turn(ms)).await?;
    Ok(())
}

fn next_delay(turn: TurnResult) -> u32 {
    if turn.immediate_work {
        0
    } else {
        // 应用每隔至多 16ms 请求再检查一次,浏览器决定实际回调时间。
        // 无休眠建议也会重查,继续处理事件引发的任务唤醒(wake-up)。
        turn.sleep_for
            .map_or(16, |duration| duration.as_millis().min(16) as u32)
    }
}

async fn drive_result<T, E: Debug>(
    result: impl Future<Output = Result<T, E>>,
    mut run_once: impl FnMut() -> Result<TurnResult, JsValue>,
) -> Result<T, JsValue> {
    let mut result = pin!(result);
    loop {
        let turn = run_once()?;
        // 只检查一次结果句柄。尚未完成时把控制权交回浏览器。
        let output = poll_fn(|cx| Poll::Ready(result.as_mut().poll(cx))).await;
        if let Poll::Ready(output) = output {
            return output.map_err(js_error);
        }
        if turn.service_closed {
            return Err(JsValue::from_str("运行时已关闭,结果仍未完成"));
        }
        yield_to_browser(next_delay(turn)).await?;
    }
}

async fn drive_close(
    mut run_once: impl FnMut() -> Result<(TurnResult, CloseState), JsValue>,
) -> Result<(), JsValue> {
    loop {
        let (turn, state) = run_once()?;
        if turn.service_closed {
            return if state == CloseState::Completed {
                Ok(())
            } else {
                Err(js_error(state))
            };
        }
        yield_to_browser(next_delay(turn)).await?;
    }
}

#[wasm_bindgen]
pub async fn local_example() -> Result<u32, JsValue> {
    use pi_async_runtime::LocalTaskDispatch;
    use std::rc::Rc;

    let mut runtime = LocalRuntime::new().map_err(js_error)?;
    let (reply, send) = wait_one();
    let (result, finish) = wait_one();
    let parent = runtime
        .spawn(async move {
            let value = Rc::new(reply.await.expect("浏览器交出输入值"));
            let _child = LocalRuntime::spawn_local(async move {
                finish
                    .send(*value * 2_u32)
                    .expect("交出本地任务(local task)结果");
            })
            .expect("在当前本地运行时(runtime)提交");
            // 释放子任务的结果句柄(result handle)只放弃领取,不取消子任务。
        })
        .map_err(js_error)?;

    runtime.run_once().map_err(js_error)?; // 先启动任务并登记等待。
    yield_to_browser(0).await?; // 让浏览器(browser)安排下一次回调。
    send.send(21_u32).map_err(js_error)?;

    let answer = drive_result(result, || runtime.run_once().map_err(js_error)).await?;
    // 父任务(Task)在子任务交值前已经返回,此处可以直接领取父任务的结果。
    parent.await.map_err(js_error)?;
    runtime.request_close();
    drive_close(|| Ok((runtime.run_once().map_err(js_error)?, runtime.close_state()))).await?;
    Ok(answer)
}

fn submit_plain_waits(
    runtime: &impl TaskDispatch,
) -> Result<impl Future<Output = Result<u32, TaskError>>, JsValue> {
    let (any, contender) = wait_any();
    let other = contender.clone();
    let (all, first) = wait_all();
    let second = first.clone();
    contender.send(12_u32).map_err(js_error)?;
    assert!(other.send(99_u32).is_err());
    first.send(10_u32).map_err(js_error)?;
    second.send(20_u32).map_err(js_error)?;
    runtime
        .spawn(async move {
            let winner = any.await.expect("取得一个值");
            let values = all.await;
            winner + *values[0].as_ref().unwrap() + *values[1].as_ref().unwrap()
        })
        .map_err(js_error)
}

#[wasm_bindgen]
pub async fn untimed_example(serial: bool) -> Result<u32, JsValue> {
    let queues = RuntimeQueues::default().without_timer().without_idle();
    let options = RuntimeOptions::default();
    // 两种类型各有自己的接纳(admission)方式,均可用普通等待(wait)。
    macro_rules! run {
        ($kind:ty) => {{
            let mut runtime = <$kind>::with_queues(options, queues).map_err(js_error)?;
            let result = submit_plain_waits(&runtime)?;
            let answer = drive_result(result, || runtime.run_once().map_err(js_error)).await?;
            runtime.request_close();
            drive_close(|| Ok((runtime.run_once().map_err(js_error)?, runtime.close_state())))
                .await?;
            Ok(answer)
        }};
    }
    if serial {
        run!(SerialRuntime)
    } else {
        run!(ConcurrentRuntime)
    }
}

③ 安装并手动刷新全局时钟(global clock)

需要默认定时任务队列(timer task queue)时,在构造第一份带定时的 LocalRuntime、SerialRuntime 或 ConcurrentRuntime 前调用一次 pi_clock_manual::global::try_init()。先初始化 JavaScript 绑定(bindings),再调用下面的 Rust 初始化入口。全局时钟(global clock)读取同一个 JavaScript 环境的 performance.now()。在单个 Wasm 实例与固定浏览器(browser)线程上使用,保持默认的无 WebAssembly 原子指令(atomics)构建。重复初始化返回 AlreadyExists。同一 Wasm 实例中的多个运行时(runtime)可以共享时钟。关闭(close)其中一个后,其它运行时仍可使用它。

三个操作可以分开理解。

  1. global::try_refresh() 采样实际经过的时间并发布。手动刷新是请时钟取一次样本。时间增长仍由浏览器提供。这个操作无需后台刷新线程(thread),也不推进队列(queue)。应用可以在每次浏览器回调(callback)开始时调用它。
  2. global::try_now() 读取最近发布的值。如果应用只读这个接口,缓存可保持旧值。调用 try_refresh 后可以读取已发布的新样本,不必等待运行时执行一轮。
  3. runtime.run_once() 接纳(admission)任务并推进定时到期和后续唤醒(wake-up)。默认 ManualClock 在需要时间时会主动调用 try_refresh。只使用运行时的定时接口时,应用只需周期性调用 run_once。只有业务还要及时读取全局时钟缓存时,才需要示例中的额外刷新。

在 src/lib.rs 末尾追加以下内容。构造等待的调用都很短,正时长从首次轮询(poll)开始。这个例子故意让一个请求缺少答复,另两种等待由发送者提交结果。

#[cfg(feature = "browser-clock")]
#[wasm_bindgen]
pub fn init_clock() -> Result<(), JsValue> {
    pi_clock_manual::global::try_init().map_err(js_error)
}

#[cfg(feature = "browser-clock")]
fn submit_timed<R: TaskDispatch + pi_async_runtime::RuntimeWait + 'static>(
    runtime: &R,
) -> Result<impl Future<Output = Result<u32, TaskError>>, JsValue> {
    use pi_async_runtime::{TimeoutError, WaitTimeoutError};
    use std::{future::pending, time::Duration};

    let short = Duration::from_millis(3);
    let delay = runtime.sleep(short);
    let deadline = runtime.timeout(short);
    let limited = runtime.timeout_on(pending::<()>(), short);
    let (expired, keep_open) = runtime.wait_one_timeout::<u32>(short);
    let (any, contender) = runtime.wait_any_timeout(short);
    let (all, first) = runtime.wait_all_timeout(short);
    let second = first.clone();
    contender.send(12_u32).map_err(js_error)?;
    first.send(10_u32).map_err(js_error)?;
    second.send(20_u32).map_err(js_error)?;

    runtime
        .spawn(async move {
            delay.await.expect("短时等待完成");
            deadline.await.expect("等待至指定时长");
            assert!(matches!(limited.await, Err(TimeoutError::Elapsed)));

            // 关联方法使用当前任务所属运行时的本地定时任务队列。
            R::sleep_local(short).unwrap().await.unwrap();
            R::timeout_local(short).unwrap().await.unwrap();
            assert!(matches!(
                R::timeout_on_local(pending::<()>(), short).unwrap().await,
                Err(TimeoutError::Elapsed),
            ));

            // 保留发送方,等待只因时限到期而结束。
            assert!(matches!(expired.await, Err(WaitTimeoutError::Elapsed)));
            drop(keep_open);
            let winner = any.await.expect("已交出的一个值");
            let values = all.await.expect("取得全部结果");
            winner + *values[0].as_ref().unwrap() + *values[1].as_ref().unwrap()
        })
        .map_err(js_error)
}

#[cfg(feature = "browser-clock")]
#[wasm_bindgen]
pub async fn timed_example(kind: String) -> Result<u32, JsValue> {
    use pi_async_runtime::{ExecutorOptions, IdleDispatch, LocalRuntimeQueues};
    use pi_async_task_queue::MpscIdleTaskQueue;

    macro_rules! run {
        ($make:expr) => {{
            let mut runtime = ($make).map_err(js_error)?;
            let result = submit_timed(&runtime)?;
            let idle = runtime.idle(async { 7_u32 }).map_err(js_error)?;
            let answer = drive_result(result, || {
                // 可选。给业务读取者发布最新样本,运行时自身也按需取时。
                let updated = pi_clock_manual::global::try_refresh().map_err(js_error)?;
                // try_now 读取刚发布或更新的时间点。
                assert!(pi_clock_manual::global::try_now().map_err(js_error)? >= updated.published);
                runtime.run_once().map_err(js_error)
            })
            .await?;
            // 本次构造也绑定空闲任务队列,继续推进可领取空闲任务结果。
            assert_eq!(drive_result(idle, || runtime.run_once().map_err(js_error)).await?, 7);
            runtime.request_close();
            drive_close(|| Ok((runtime.run_once().map_err(js_error)?, runtime.close_state())))
                .await?;
            Ok(answer)
        }};
    }
    match kind.as_str() {
        "serial" => run!(SerialRuntime::new()),
        "concurrent" => run!(ConcurrentRuntime::new()),
        "local" => {
            // 本地运行时独立选配两项,同一线程仍负责提交并逐轮推进。
            let idle = MpscIdleTaskQueue::new(Default::default()).map_err(js_error)?;
            let queues = LocalRuntimeQueues::default().with_default_timer().with_idle(idle);
            run!(LocalRuntime::with_queues(ExecutorOptions::default(), queues))
        }
        _ => Err(JsValue::from_str("未知的运行时类型")),
    }
}
接口(API) 使用方式
sleep(duration)、timeout(duration) 等待指定时长。正 sleep 支持 1 毫秒到 1 秒。正 timeout 从 1 毫秒起,可用其控制句柄(TimeoutControl)请求取消。
timeout_on(future, duration) 先尝试业务异步计算(Future)。业务挂起(Pending)后开始计时,同轮就绪时优先取业务结果,到期返回 TimeoutError::Elapsed。由应用单独派发的任务(Task)仍按其控制句柄(TaskControl)管理。
sleep_local、timeout_local、timeout_on_local 在实际类型的活动本地任务(local task)或有效本地范围内调用。先处理关联方法返回的本地访问错误,再 .await 异步结果。
wait_one、wait_any、wait_all 返回等待值和发送者(sender)。wait_one 接收一个值,wait_any 由任一发送者赢得交值,wait_all 按登记顺序返回每项结果。
wait_one_timeout、wait_any_timeout、wait_all_timeout 带时限的对应入口。前两项用 WaitTimeoutError::Elapsed 表示超时,最后一项用 TimeoutError::Elapsed,超时时无部分结果。计时设施错误(timer error)另行返回。

串行运行时(serial runtime)会等本地在途任务和内部任务队列(internal task queue)都清空,才接纳下一批普通外部任务。当前任务挂起时,已经接纳的任务仍可推进。请让浏览器回调(callback)、已经接纳的任务或本地任务(local task)交值,避免等待尚未接纳的下一批普通外部任务。

④ 构建、装载并运行示例

保存为 web/index.html。浏览器完成 Wasm 模块初始化后运行三个不需要时钟的示例。启用定时时,再安装时钟并验证三种带定时的运行时(runtime)。

<!doctype html>
<html lang="zh">
<meta charset="utf-8">
<title>Wasm32 运行时示例</title>
<pre id="result">运行中</pre>
<script type="module">
const result = document.querySelector("#result");
try {
    const demo = await import("./pkg/browser_runtime_example.js");
    await demo.default();
    const local = await demo.local_example();
    const untimedSerial = await demo.untimed_example(true);
    const untimedConcurrent = await demo.untimed_example(false);
    let timed = "未启用";
    if (demo.init_clock && demo.timed_example) {
        demo.init_clock();
        timed = [
            await demo.timed_example("serial"),
            await demo.timed_example("concurrent"),
            await demo.timed_example("local"),
        ].join(", ");
    }
    result.textContent = `本地=${local};无定时=${untimedSerial}, ${untimedConcurrent};默认定时=${timed}`;
    if ([local, untimedSerial, untimedConcurrent].every(value => value === 42)
        && (timed === "未启用" || timed === "42, 42, 42")) {
        result.dataset.status = "ok";
    }
} catch (error) {
    result.textContent = String(error?.stack || error);
    result.dataset.status = "error";
}
</script>

安装示例使用的工具链和标准库源码,再编译并生成浏览器加载所需的 JavaScript。下面从应用目录运行。用 cargo tree 取得解析后的绑定版本,命令行工具(CLI)需要与其匹配。两个构建可以复用同版本的 CLI。Cargo 构建标准库 · wasm-bindgen 命令行文档

rustup toolchain install nightly-2026-07-19 --profile minimal --component rust-src
cargo +nightly-2026-07-19 build --target wasm32-unknown-unknown -Zbuild-std=std,panic_abort
bindgen_version="$(cargo +nightly-2026-07-19 tree --target wasm32-unknown-unknown -i wasm-bindgen --depth 0 --prefix none | sed -n '1s/^wasm-bindgen v//p')"
cargo +nightly-2026-07-19 install wasm-bindgen-cli --version "=$bindgen_version" --locked
wasm-bindgen --target web --out-dir web/pkg target/wasm32-unknown-unknown/debug/browser_runtime_example.wasm
python3 -m http.server 8080 --bind 127.0.0.1 --directory web

如果已为同一工具链安装预编译的 wasm32-unknown-unknown 标准库,可在 cargo build 中省略 -Zbuild-std=std,panic_abort。要构建省略定时的版本,给 cargo build 加 --no-default-features,然后重新生成 web/pkg。浏览器打开本机的 http://127.0.0.1:8080/,默认版本显示“本地=42;无定时=42, 42;默认定时=42, 42, 42”。省略定时的版本在最后显示“未启用”。

计时、空闲与结果

正时长 timeout 在首次轮询才开始登记;timeout_on 同轮优先观察业务完成,业务完成后处理不再需要的计时等待。正超时支持至少1ms,也允许超过1s;sleep 的正时长范围为1ms至1s。

零超时等价于让出一次,不建立正时长登记,不能成功取消。yield_now 是惰性异步函数,只有被轮询才让出;它不承诺运行所有其它任务或等待外部通知。

在运行时(runtime)中使用本地派发和本地计时

两种模式的本地调用都使用当前所属线程(owner thread)的有效访问。下面的串行运行时使用 spawn_local 推进子任务,子任务携带不可跨线程的 Rc。在根异步计算(root Future)中也能用 timeout_on_local 等待借用栈数据的异步计算(Future)。

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)取消

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)

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 的同步选择范围。创建或推进本地任务仍要求运行时真实具有相应的本地访问。

分开创建与提交,并处理停收拒绝

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。