易用
异步程序统一以 faio::task<T>
协程任务类型组织,并统一使用 C++20
协程标准关键字,从而降低异步程序编写的复杂性。
异步程序统一以 faio::task<T>
协程任务类型组织,并统一使用 C++20
协程标准关键字,从而降低异步程序编写的复杂性。
基于现代 C++ 编写,提供多线程任务窃取调度器,充分利用多核并行能力,并且针对性优化了协程帧内存分配。
运行时提供单线程和多线程两种模式;任务提供可配置属性,如是否可被窃取、是否绑核运行。
遵循现代 C++ 的 RAII 开发原则进行内存管理;错误处理统一采用
std::expected,并且
faio::task<T>
提供了完善的异常处理链和错误处理链,支持任务的协作取消。
#include <faio/faio.hpp>
#include <chrono>
#include <print>
using namespace std::chrono_literals;
faio::task<void> hello() {
co_await faio::time::sleep(10ms);
std::print("Hello, world!\n");
}
faio::task<void> run() {
co_await faio::join(hello());
}
int main() {
faio::block_on(run());
}
#include <faio/faio.hpp>
#include <array>
#include <exception>
#include <span>
#include <utility>
namespace {
const auto address = faio::net::SocketAddr{faio::net::Ipv4Addr{127, 0, 0, 1}, 8080};
faio::task<void> handle_connection(faio::net::TcpStream stream,
faio::net::SocketAddr peer) {
std::array<char, 4096> buffer{};
for (;;) {
const auto count = co_await stream.read(buffer);
if (!count) {
faio::log::logger()->error("读取 {} 失败:{}", peer.to_string(), count.error().message());
co_return;
}
if (*count == 0) {
faio::log::logger()->info("{} 已关闭连接", peer.to_string());
co_return;
}
const auto written =
co_await stream.write_all(std::span<const char>{buffer}.first(*count));
if (!written) {
faio::log::logger()->error("写回 {} 失败:{}", peer.to_string(), written.error().message());
co_return;
}
}
}
faio::task<int> serve() {
auto listener = faio::net::TcpListener::bind(address);
if (!listener) {
faio::log::logger()->error("绑定 {} 失败:{}", address.to_string(), listener.error().message());
co_return 1;
}
faio::log::logger()->info("TCP 回显服务监听 {}", address.to_string());
for (;;) {
auto accepted = co_await listener->accept();
if (!accepted) {
faio::log::logger()->error("接受连接失败:{}", accepted.error().message());
co_return 1;
}
auto [stream, peer] = std::move(*accepted);
faio::log::logger()->info("接受来自 {} 的连接", peer.to_string());
faio::spawn_detached(handle_connection(std::move(stream), peer));
}
}
}
int main() {
try {
return faio::block_on(serve());
} catch (const std::exception& error) {
faio::log::logger()->error("TCP 回显服务异常退出:{}", error.what());
return 1;
}
}
faio::task<T> 是最基本的并发与调度单元,惰性创建、移动独占。提供丰富的并发组合、协作取消与调度属性设置。
提供多线程工作窃取与单线程两种运行模式,支持配置 worker 数量、阻塞任务上限与文件服务线程,并可按策略有序停机。
提供 TCP、UDP、Unix 域套接字与地址解析,网络失败以 expected 返回,I/O 操作支持设置超时。
提供异步文件与目录操作,支持缓冲读写与显式偏移,句柄移动独占,文件读写不占用协程 worker。
提供互斥、条件变量、信号量、闩、屏障与有界通道,等待期间挂起任务而不阻塞线程,唤醒后回到原调度上下文。
为已建立的流提供加密封装,握手与字节读写沿用同一套异步接口。客户端始终验证证书链与主机名,并支持 ALPN 协商。
提供 Command 描述程序、参数与标准 IO,支持 spawn() 启动子进程、output() 捕获输出与超时终止。
提供 C++26 注解入口,免去传统 main 函数,改用协程作为程序起点;同时支持与 std::execution Sender/Receiver 接口的互操作。