Asynchronous I/O
File and socket operations in ConcurrentTasks are asynchronous operations of the operating system: overlapped I/O on the core's I/O completion port on Windows, io_uring on Linux. A task starts an operation and is suspended; when the operation completes, the core's I/O thread resumes it. No thread blocks in between.
Enabling asynchronous I/O
AsyncIo::EnableAsyncIo creates the completion port (Windows) or the io_uring instance (Linux) and the I/O thread that drains it; AsyncIo::DisableAsyncIo takes it back. The calls are counted, so a library and the application can both enable it.
Important
Enable asynchronous I/O before you create files or sockets, and disable it only when no operation is pending any more.
How an operation runs
- On Windows a file or socket is opened for overlapped I/O and associated with the port
(AssociateHandleWithIoCompletionPort);
AsyncFile and AsyncSocket do this in their
Create. On Linux nothing has to be registered: every operation names its file descriptor. - Each operation carries a request object that owns the platform's request structure
(AsyncIoRequestBase): the
OVERLAPPEDof the Win32 call on Windows, the core'sIoRequest, which SubmitIo hands to io_uring, on Linux. - When the operation completes, the I/O thread passes the result to the request (RequestCompleted). A waitable request sets an event, which resumes the waiting task.
- On Windows an operation that completes at once is completed on the calling thread, and no completion packet follows. On Linux every operation the core accepted completes on the I/O thread.
Waiting and starting forms
The library offers each operation in two forms:
- Waiting — AsyncFile::Read, AsyncSocket::Recv and so on start the operation and suspend the calling task until it completes, optionally with a timeout. They need a task or a converted thread.
- Starting — AsyncFile::ReadAsync, AsyncSocket::RecvAsync and so on only start the operation and return. You wait later on the request (for example a WaitableAsyncFileIoRequest), which lets one task keep several operations in flight.
On top of that, AsyncFile::ReadFile and WriteFile move a whole file through a sequential memory with several requests in flight, and StreamedFileReader and OrderedFileWriter stream large files with bounded memory.
Important
A request and its buffer must stay alive and in place until the operation has completed. Close or destroy a file or socket only when no operation on it is pending.
Errors
File operations return ErrorCode and socket operations
SocketErrorCode: Win32 and Winsock codes on Windows, errno values on Linux,
0 on success in both. The starting forms may also return the "pending" code of their API; on Linux
every operation that was started returns it.