簡體   English   中英

使用Boost.Asio鏈接異步Lambda?

[英]Chaining asynchronous Lambdas with Boost.Asio?

我發現自己編寫的代碼基本上是這樣的:

using boost::system::error_code;

socket.async_connect(endpoint, [&](error_code Error)
{
  if (Error)
  {
    print_error(Error);
    return;
  }

  // Read header
  socket.async_read(socket, somebuffer, [&](error_code Error, std::size_t N)
  {
    if (Error)
    {
      print_error(Error);
      return;
    }

    // Read actual data
    socket.async_read(socket, somebuffer, [&](error_code Error, std::size_t N)
    {
      // Same here...
    });
  });
};

所以基本上我在回調中的回調中嵌套回調,而邏輯很簡單並且是“線性的”。

是否有更優雅的方式來編寫它,以便代碼是本地的和有序的?

一個優雅的解決方案是使用協同程序。 Boost.Asio支持無堆棧協程,它引入了一小組偽關鍵字,以及堆棧協程,它們使用Boost.Coroutine


Stackless Coroutines

Stackless協程引入了一組偽關鍵字預處理器宏,它們使用類似於Duff的Device的技術實現switch語句。 文檔詳細介紹了每個關鍵字。

當使用無堆棧協程實現時,原始問題(connect-> read header-> read body)可能類似於以下內容:

struct session
 : boost::asio::coroutine
{
  boost::asio::ip::tcp::socket socket_;
  std::vector<char> buffer_;
  // ...

  void operator()(boost::system::error_code ec = boost::system::error_code(),
                  std::size_t length = 0)  
  {
    // In this example we keep the error handling code in one place by
    // hoisting it outside the coroutine. An alternative approach would be to
    // check the value of ec after each yield for an asynchronous operation.
    if (ec)
    {
      print_error(ec);
      return;
    }

    // On reentering a coroutine, control jumps to the location of the last
    // yield or fork. The argument to the "reenter" pseudo-keyword can be a
    // pointer or reference to an object of type coroutine.
    reenter (this)
    {
      // Asynchronously connect. When control resumes at the following line,
      // the error and length parameters reflect the result of
      // the asynchronous operation.
      yield socket_.async_connect(endpoint_, *this);

      // Loop until an error or shutdown occurs.
      while (!shutdown_)
      {
        // Read header data. When control resumes at the following line,
        // the error and length parameters reflect the result of
        // the asynchronous operation.
        buffer_.resize(fixed_header_size);
        yield socket_.async_read(boost::asio::buffer(buffer_), *this);

        // Received data.  Extract the size of the body from the header.
        std::size_t body_size = parse_header(buffer_, length);

        // If there is no body size, then leave coroutine, as an invalid
        // header was received.
        if (!body_size) return;

        // Read body data. When control resumes at the following line,
        // the error and length parameters reflect the result of
        // the asynchronous operation.
        buffer_.resize(body_size);
        yield socket_.async_read(boost::asio::buffer(buffer_), *this);

        // Invoke the user callback to handle the body.
        body_handler_(buffer_, length);
      }

      // Initiate graceful connection closure.
      socket_.shutdown(tcp::socket::shutdown_both, ec);
    } // end reenter
  }
}

Stackful Coroutines

使用spawn()函數創建堆棧協同程序。 使用堆棧協程實現時,原始問題可能類似於以下內容:

boost::asio::spawn(io_service, [&](boost::asio::yield_context yield)
  {
    boost::system::error_code ec;
    boost::asio::ip::tcp::socket socket(io_service);

    // Asynchronously connect and suspend the coroutine.  The coroutine will
    // be resumed automatically when the operation completes.
    socket.async_connect(endpoint, yield[ec]);
    if (ec)
    {
      print_error(ec);
      return;
    }

    // Loop until an error or shutdown occurs.
    std::vector<char> buffer;
    while (!shutdown)
    {
      // Read header data.
      buffer.resize(fixed_header_size);
      std::size_t bytes_transferred = socket.async_read(
        boost::asio::buffer(buffer), yield[ec]);

      if (ec)
      {
        print_error(ec);
        return;
      }

      // Extract the size of the body from the header.
      std::size_t body_size = parse_header(buffer, bytes_transferred);

      // If there is no body size, then leave coroutine, as an invalid header
      // was received.
      if (!body_size) return;

      // Read body data.
      buffer.resize(body_size);
      bytes_transferred =
        socket.async_read(boost::asio::buffer(buffer), yield[ec]);

      if (ec)
      {
        print_error(ec);
        return;
      }

      // Invoke the user callback to handle the body.
      body_handler_(buffer, length);
    }

    // Initiate graceful connection closure.
    socket.shutdown(tcp::socket::shutdown_both, ec);
   });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM