boost::asio::spawn yield as callback

前端 未结 3 497
终归单人心
终归单人心 2020-12-28 08:57

I\'m trying to rewrite a project using boost::asio::spawn coroutines. Some parts of the project cannot be changed. For example, the storage protocol library is

3条回答
  •  被撕碎了的回忆
    2020-12-28 09:37

    Thanks to @PSIAlt and @free_coffee I know how to use callback functions in stackful coroutine.

    Here is a simple example just for asio newbies(like me :D)

    https://gist.github.com/chenfengyuan/4d764b0bca82a42c05a9

    #include 
    #include 
    #include 
    #include 
    #include 
    
    void bar(boost::asio::io_service &io, std::function cb){
        auto ptr = std::make_shared(io, boost::posix_time::seconds(1));
        ptr->async_wait([ptr, cb](const boost::system::error_code&){cb();});
    }
    
    template
    void foo(boost::asio::io_service &io, Handler && handler){
        typename boost::asio::handler_type::type handler_(std::forward(handler));
        boost::asio::async_result result(handler_);
        bar(io, handler_);
        result.get();
        return;
    }
    
    int main()
    {
      boost::asio::io_service io;
      boost::asio::spawn(io, [&io](boost::asio::yield_context yield){
          foo(io, yield);
          std::cout << "hello, world!\n";
      });
    
      io.run();
    
      return 0;
    }
    

提交回复
热议问题