栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

boost 协程+异步

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

boost 协程+异步

简单演示代码

#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})
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/935400.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号