c++ boost 使用coroutine协程

CMake工程

主要是要包含coroutine的库

cmake_minimum_required (VERSION 3.12)
MESSAGE(STATUS "CMAKE_ROOT: " ${CMAKE_ROOT})

project(cpp-demo VERSION 0.0.1 LANGUAGES CXX)

find_package(Boost REQUIRED COMPONENTS system thread filesystem coroutine)

SET(CMAKE_BUILD_TYPE "Debug")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -pthread -g -W")

aux_source_directory(. DIRSRCS)

add_executable(${PROJECT_NAME}
    ${DIRSRCS})

target_link_libraries(${PROJECT_NAME} 
    ${Boost_LIBRARIES})

案例一:等待消息

#include <boost/coroutine/all.hpp>
#include <iostream>

using boost::coroutines::coroutine;

struct Task
{
  int id{0};

  Task(){}
  Task(int t_id)
  {
    id = t_id;
  }
};

void run(coroutine<Task>::pull_type &wait_msg)
{
  while(true)
  {
    //获取参数
    auto taskInfo = wait_msg.get();
    //结束
    if (taskInfo.id<=0)
    {
      std::cout<<"run task end..."<<std::endl;
      break;
    }
    std::cout<<"run task..."<<taskInfo.id<<std::endl;

    //等待下一条消息
    wait_msg();
  }
}

int main()
{
  coroutine<Task>::push_type task_executor{run};

  for (size_t i = 1; i < 3; i++)
  {
    //发送消息
    task_executor(Task(i));
  }
  //发送结束消息
  task_executor(Task());

  std::cout <<"all tasks finished..."<<std::endl;
}

等待消息进来,然后执行
运行结果:

./build/cpp-demo
run task...1
run task...2
run task end...
all tasks finished...
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值