• Boost ASIO: Coroutines


    Abstract

    Since version 1.54.0, Boost.Asio supports coroutines. While you could use Boost.Coroutine directly, explicit support of coroutines in Boost.Asio makes it easier to use them.

    Coroutines let you create a structure that mirrors the actual program logic. Asynchronous operations don’t split functions, because there are no handlers to define what should happen when an asynchronous operation completes. Instead of having handlers call each other, the program can use a sequential structure.

    从版本1.54.0开始,Boost。Asio支持协同程序。而您可以使用Boost。直接协程,在Boost中显式支持协程。Asio使它们更容易使用。

    Demo

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    using namespace boost::asio;
    using namespace boost::asio::ip;
    
    io_service ioservice;
    tcp::endpoint tcp_endpoint{tcp::v4(), 2014};
    tcp::acceptor tcp_acceptor{ioservice, tcp_endpoint};
    std::list tcp_sockets;
    
    void do_write(tcp::socket &tcp_socket, yield_context yield)
    {
      std::time_t now = std::time(nullptr);
      std::string data = std::ctime(&now);
      async_write(tcp_socket, buffer(data), yield);
      tcp_socket.shutdown(tcp::socket::shutdown_send);
    }
    
    void do_accept(yield_context yield)
    {
      for (int i = 0; i < 2; ++i)
      {
        tcp_sockets.emplace_back(ioservice);
        tcp_acceptor.async_accept(tcp_sockets.back(), yield);
        spawn(ioservice, [](yield_context yield)
          { do_write(tcp_sockets.back(), yield); });
      }
    }
    
    int main()
    {
      tcp_acceptor.listen();
      spawn(ioservice, do_accept);
      ioservice.run();
    }

    Asio boost:: Asio:: spawn()。传递的第一个参数必须是一个I/O服务对象。第二个参数是将作为协程的函数。这个函数必须接受boost::asio::yield_context类型的对象作为它的唯一参数。它必须没有返回值。例32.7使用do_accept()和do_write()作为协程。如果函数签名不同,如do_write()的情况,则必须使用std::bind或lambda函数等适配器。

  • 相关阅读:
    Gartner:55%的组织,正在试用ChatGPT等生成式AI
    MAC 地址简化概念(有线 MAC 地址、无线 MAC 地址、MAC 地址的随机化)
    NameNode故障处理的两种方法
    Python例题练习1
    Python爬虫实战第一例【一】
    在WSL中使用code . 启动vscode失败 解决
    DAY55 583. 两个字符串的删除操作 + 72. 编辑距离
    【数据挖掘】聚类分析的简要介绍
    #AcWing--合并两个排序的链表
    Spring MVC简介及核心组件和调用流程理解
  • 原文地址:https://blog.csdn.net/qq_32378713/article/details/126596858