Ch26.10: Async I/O

中文(简体)

1. The Object Model

Object Role Ownership
::fast_io::io_async_scheduler The OS backend: io_uring on Linux, IOCP/IoRing on Windows, a thread pool on other POSIX targets. Owned by the program, usually one per event loop.
::fast_io::io_async_observer A small, copyable, non-owning view of the scheduler. Borrowed; the scheduler must outlive it.
::fast_io::io_async_task<T> Lazy coroutine task; owns its frame and can be resumed, awaited or detached. Move-only; destroys the frame when the task object dies.
::fast_io::io_async_wait(sched) The event pump: wait for one completion, dispatch it, resume the waiting coroutine. Called by the program's supervisor loop.

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

The scheduler is created with the io_async tag. Passing the owning scheduler where an observer is expected decays automatically, exactly as an owning file decays to its observer.

2. io_async_task

io_async_task<T> is lazy: creating it does not run the coroutine body. resume() enters or continues it; done() reports completion; rethrow_if_error() turns a stored herbception back into a throw.

Member Meaning
resume() Start or continue the coroutine until it suspends or finishes.
done() True when the frame has finished or the task no longer owns one.
detach() Release ownership, mark the frame detached and start it. The frame destroys itself at completion.
rethrow_if_error() Rethrow a stored error through the herbception channel.
native_handle() The underlying std::coroutine_handle.
co_await task Await a child task; the result is moved out on success, errors are rethrown.

A task that is neither awaited nor detached has its frame destroyed when the task object dies. A detached task's failure is silent unless the coroutine handled it itself.

3. The Async Operations

The async surface mirrors the synchronous one. Each operation takes the scheduler, a timeout, the device, and the operation-specific arguments; the coroutine form returns an awaiter.

Operation Signature Returns
async_scan (sched, timeout, in, args...) An awaiter; co_await scans the values.
async_scan_some (sched, timeout, in, args...) scan_some_result_t for partial input.
async_print, async_println (sched, timeout, out, args...) An awaiter; co_await writes the formatted bytes.
async_transmit_some_bytes (sched, timeout, out, off_out, in, off_in, bound) Bytes moved in this round; 0 means EOF.
async_transmit_all_bytes same signature Completes when the bound or EOF is reached.
async_accept (sched, timeout, listener, mode = {}) Native accepted handle; wrap it in a socket file.
async_connect (sched, timeout, socket, addr, addrlen) Completes when connected; the socket is reused, not consumed.
async_output_stream_flush (sched, timeout, out) Completes when pending output reaches the device.
async_pread_some_bytes, async_pwrite_some_bytes (sched, timeout, stream, buf, count, off) Bytes moved; low-level byte windows.

The high-level rule is the same as the synchronous layer: scan for input, print for output, transmit for byte movement. Dropping to async_pread/async_pwrite means taking over buffering and partial transfer handling again.

4. The Smallest Loop


::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() enters the coroutine. The first co_await submits the read and suspends. io_async_wait reaps the completion and resumes the frame. The loop repeats until the task is done. The event loop is single-threaded; the kernel or thread pool does the waiting.

5. Backends and Errors

Platform Backend Wait primitive
Linux io_uring io_async_wait, io_async_peek, io_async_wait_timeout
Windows IOCP or IoRing the same wait family
Other POSIX thread pool the same wait family

Operation failures surface through the herbception channel: an awaited operation throws, rethrow_if_error() rethrows a stored error, and a detached task's unhandled error is discarded with the frame. Timeouts are passed as posix_statx_timestamp_opt; {} means no timeout.

6. Ownership and Lifetime Rules

Key Takeaways