Replies: 1 comment 1 reply
-
先按 POSIX 接口设计你的程序,然后将需要异步的系统调用换成 co_context::lazy 提供的 API 即可。对于文件 IO,通常会用到 例如,下面这段程序将打印 #include "co_context/all.hpp"
#include <iostream>
#include <string_view>
#include <vector>
using namespace co_context;
void check_error(int err) {
std::cerr << strerror(err) << std::endl;
}
task<void> head(const char *path, size_t len) {
int fd = ::open(path, O_RDONLY);
if (fd < 0) {
check_error(errno);
co_return;
}
std::vector<char> buffer(len);
int nr = co_await read(fd, buffer, 0);
if (nr < 0) {
check_error(-nr);
co_return;
}
std::string_view content{buffer.data(), (size_t)nr};
std::cout << content << std::endl;
::close(fd);
}
int main() {
io_context ctx;
ctx.co_spawn(head("/etc/profile", 1000));
ctx.start();
ctx.join();
return 0;
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
迫不及待想用了
Beta Was this translation helpful? Give feedback.
All reactions