简单演示代码
#include#include #include #include using namespace std; using namespace boost; asio::io_service ioService; //异步任务管理器 asio::thread_pool threadPool(1); //运行异步任务的线程池 //协程1运行的函数 void fun1() { while (1) { //同步用的,每次使用前都需要初始化 boost::fibers::promise promise; boost::fibers::future future(promise.get_future()); cout << "协程1运行" << endl; //创建异步任务,并post到异步任务管理器 ioService.post([&]() { cout << "异步任务1运行开始" << endl; //延时5s boost::this_thread::sleep(boost::get_system_time() + boost::posix_time::seconds(5)); //返回异步结果 promise.set_value(1); }); //进入协程调度并等待异步任务结果 int a = future.get(); cout << "协程1结果: " << a << endl; } } //协程2运行的函数 void fun2() { while (1) { cout << "协程2运行" << endl; //延时1s boost::this_thread::sleep(boost::get_system_time() + boost::posix_time::seconds(1)); //进入协程调度 this_fiber::yield(); } } //线程池运行的函数 void fun_loop1() { cout << "fun_loop1" << endl; //设置异步任务管理器在无任务时处于等待状态 boost::asio::io_service::work work(ioService); //运行异步任务管理器 ioService.run(); } int main() { //通过线程池启动异步任务管理器 asio::post(threadPool, fun_loop1); //创建两个协程 fibers::fiber fiber1(fun1); fibers::fiber fiber2(fun2); //协程调度 fiber1.join(); fiber2.join(); getchar(); return 0; }
运行结果
协程1运行 fun_loop1 异步任务1运行开始 协程2运行 协程2运行 协程2运行 协程2运行 协程2运行 协程2运行 协程1结果: 1 协程1运行 协程2运行 异步任务1运行开始 协程2运行 协程2运行 协程2运行 协程2运行 协程2运行 协程1结果: 1 协程1运行
cmake 配置
cmake_minimum_required(VERSION 3.22)
project(demo1)
set(CMAKE_CXX_STANDARD 14)
find_package(Boost REQUIRED COMPONENTS thread atomic fiber thread coroutine context)
include_directories(${Boost_INCLUDE_DIRS})
link_directories(${Boost_LIBRARY_DIRS})
add_executable(demo1 main2.cpp)
target_link_libraries(demo1 ${Boost_LIBRARIES})



