第26.10章:异步 I/O

English

1. 对象模型

对象 角色 所有权
::fast_io::io_async_scheduler OS 后端:Linux 上是 io_uring,Windows 上是 IOCP/IoRing, 其他 POSIX 上是线程池。 程序拥有,通常每个事件循环一个。
::fast_io::io_async_observer scheduler 的小型、可复制、非拥有视图。 借用;scheduler 必须比它活得久。
::fast_io::io_async_task<T> 惰性协程任务;拥有自己的 frame,可以被 resume、await 或 detach。 只能移动;任务对象销毁时销毁 frame。
::fast_io::io_async_wait(sched) 事件泵:等待一个完成、分派它、恢复等待中的协程。 由程序的监督循环调用。

::fast_io::io_async_scheduler sched{::fast_io::io_async};
::fast_io::io_async_observer obs{sched};

scheduler 用 io_async 标签创建。把拥有它的 scheduler 传给需要 observer 的地方时, 会自动 decay,和拥有文件退化为 observer 完全一样。

2. io_async_task

io_async_task<T> 是惰性的:创建它不会运行协程体。 resume() 进入或继续它;done() 报告完成; rethrow_if_error() 把保存的 herbception 重新抛出。

成员 含义
resume() 开始或继续协程,直到它挂起或结束。
done() frame 已结束,或任务不再拥有 frame 时为真。
detach() 释放所有权,标记 frame 为 detached 并启动它。完成时 frame 自己销毁。
rethrow_if_error() 通过 herbception 通道重新抛出保存的错误。
native_handle() 底层的 std::coroutine_handle。
co_await task 等待子任务;成功时移出结果,错误重新抛出。

既没有被 await 也没有被 detach 的任务,在任务对象销毁时销毁 frame。 detached 任务的失败是静默的,除非协程自己处理了它。

3. 异步操作

异步表面镜像同步表面。每个操作接收 scheduler、timeout、设备,以及操作特定的参数; 协程形式返回 awaiter。

操作 签名 返回
async_scan (sched, timeout, in, args...) awaiter;co_await 扫描值。
async_scan_some (sched, timeout, in, args...) 部分输入时返回 scan_some_result_t。
async_print、async_println (sched, timeout, out, args...) awaiter;co_await 写出格式化字节。
async_transmit_some_bytes (sched, timeout, out, off_out, in, off_in, bound) 这一轮搬了多少字节;0 表示 EOF。
async_transmit_all_bytes 相同签名 到达 bound 或 EOF 时完成。
async_accept (sched, timeout, listener, mode = {}) 原生 accepted handle;包进 socket 文件。
async_connect (sched, timeout, socket, addr, addrlen) 连接完成;socket 被复用,不被消耗。
async_output_stream_flush (sched, timeout, out) 挂起输出到达设备时完成。
async_pread_some_bytes、async_pwrite_some_bytes (sched, timeout, stream, buf, count, off) 传输的字节数;底层字节窗口。

高层规则和同步层相同:输入用 scan,输出用 print,字节移动用 transmit。 降到 async_pread/async_pwrite 意味着你又接管了缓冲和部分传输处理。

4. 最小循环


::fast_io::io_async_task<> work(::fast_io::io_async_observer sched) throws
{
    ::fast_io::ibuf_file in{"input.txt", ::fast_io::open_mode::in};
    int a{};
    int b{};
    co_await ::fast_io::async_scan(sched, {}, in, a, b);
    co_await ::fast_io::async_println(sched, {}, ::fast_io::out(), a + b);
}

int main()
try
{
    ::fast_io::io_async_scheduler sched{::fast_io::io_async};
    auto task{work(sched)};
    task.resume();
    while (!task.done())
    {
        ::fast_io::io_async_wait(sched);
    }
    task.rethrow_if_error();
}
catch throws(::std::error e)
{
    ::fast_io::perrln(e);
    return 1;
}

task.resume() 进入协程。第一个 co_await 提交读并挂起。 io_async_wait 收割完成并恢复 frame。循环直到任务完成。 事件循环是单线程的;等待由内核或线程池完成。

5. 后端与错误

平台 后端 等待原语
Linux io_uring io_async_wait、io_async_peek、 io_async_wait_timeout
Windows IOCP 或 IoRing 同一组等待原语
其他 POSIX 线程池 同一组等待原语

操作失败通过 herbception 通道浮出:被 await 的操作抛出, rethrow_if_error() 重新抛出保存的错误,detached 任务的未处理错误随 frame 丢弃。 超时用 posix_statx_timestamp_opt 传入;{} 表示没有超时。

6. 所有权与生命周期规则

要点