如果您不熟悉 io_uring 和 c++20 协程,可以参考这个仓库里的其他一些文章和示例代码:
github.com/yunwei37/co-uring-WebServer
这个版本的 echo server 代码由 https://github.com/frevib/io_uring-echo-server 改造而来,是希望通过在 io_uring 的基础上,尝试实现最基本的协程 IO 模式,然后进行性能对比。之前的版本使用了一个 event loop 的模式,并通过 io_uring 的 IORING_OP_PROVIDE_BUFFERS 参数和 IORING_FEAT_FAST_POLL 参数,实现了零拷贝和内核线程的 polling,不需要额外的系统调用开销。
本文在 io_uring-echo-server 的基础上增添了一个简易的协程实现,完整的 demo 代码实现在这里:github.com/yunwei37/co-uring-WebServer/blob/master/demo/io_uring_coroutine_echo_server.cpp
协程实现
原先的代码包含一个 event loop,大致是这样(忽略具体细节),进行 IO 和完成 IO 的逻辑是完全分开的:
add_accept(....);
// start event loop
while (1) {
io_uring_for_each_cqe(&ring, head, cqe) {
if (type == ACCEPT) {
add_read(....);
add_accept(....);
} else if (type == READ) {
if (read_cout <= 0) {
close();
}
add_write(....);
} else if (type == WRITE) {
add_read(....);
}