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...