boost asio协程自定义挂起与唤醒操作

#include <iostream>
#include <cstdint>
#include <array>
#include <queue>
#include <functional>
#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/noncopyable.hpp>
#include <boost/system/error_code.hpp>
#include <queue>

class Dummy{

    private:
        std::queue<boost::asio::detail::wait_op*>wait_queue_;
        template <typename Handler>
        void async_wait_impl(Handler& handler){
            typedef boost::asio::detail::wait_handler <Handler> op;
            typename op::ptr p = { boost::asio::detail::addressof(handler),op::ptr::allocate(handler), 0 };
            p.p = new (p.v) op(handler);
            wait_queue_.push(p.p);
            p.v = p.p = 0;
        }

    public:
        template <typename WaitHandler>
        BOOST_ASIO_INITFN_RESULT_TYPE(WaitHandler,
            void (boost::system::error_code))
         async_wait(WaitHandler&&handler){
            boost::asio::async_completion<WaitHandler,void (boost::system::error_code)> init(handler);
            async_wait_impl(init.completion_handler);
            return init.result.get();
        }

        void Notify(void){
            
            if(wait_queue_.size()<=0)return;
            auto waiting_item = wait_queue_.front();
            wait_queue_.pop();
            waiting_item->complete(this,boost::system::error_code(),0);
        }
};


Dummy dump;
boost::asio::io_context ioc_;
boost::asio::io_context::work idle_worker (ioc_);

void coro1(boost::asio::yield_context yield){

    boost::system::error_code ec;

    while(1){
        dump.async_wait(yield[ec]);
        std::cout<<"coro1 wake up"<<std::endl;
    }

}

void coro2(boost::asio::yield_context yield){

    boost::asio::steady_timer timer(ioc_);
    boost::system::error_code ec;

    while(true){
        timer.expires_after(std::chrono::seconds(5));
        timer.async_wait(yield[ec]);
        dump.Notify();
    }
}

       
int main(int argc,char* argv[]){

    boost::asio::spawn(ioc_,coro1);
    boost::asio::spawn(ioc_,coro2);
    ioc_.run();
}

有时候为了更好的使自己的程序和boost asio协程配合,需要自定义挂起与唤醒协程(生产者与消费者场景)。本例代码提供一种参考方法。

该程序使用boost1_67版本测试没问题。由于各个boost版本的内容有所不同,而代码中使用了boost具体实现的一些代码,所以代码在有些版本可能无法使用。

程序创建了两个协程,coro2定时唤醒Dummy对象上的等待对象。coro1一直循环等待Dummy对象被唤醒,唤醒后打印调试信息。

编译指令:g++ main.cc -lboost_system -lpthread -g -lboost_coroutine -DBOOST_COROUTINES_NO_DEPRECATION_WARNING

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值