io_context :: strand是否可以保证async_ *完成处理程序和自定义函子之间的顺序?

时间:2018-11-28 08:50:04

标签: boost-asio boost-beast

在这种情况下,我需要先“准备”一个async_read操作以进行读取,然后再调用自定义函数,该函数在websocket的对应部分发送内容。我将async_read的完成处理程序包裹在我将函子发布到的同一行中。

问题在于有时不调用on :: read,因此基本上我认为在ws_1处于“读取”状态之前调用了writeFromCounterpart()。

我的理解是strand在保证完成处理程序之间的顺序,但是我不理解在继续从strand FIFO进行其他操作之前,是否保证async_ *操作是“ ready”(在其线程中运行并读取) 。

下面是完整的代码:在运行它时,大多数时候我都看到以下输出:

on_read called
Run 2 Handlers

我也能看几次以下内容(在压力状态下,约20分之一),

on_write called
Run 1 Handlers

我从没见过on_write和on_read

代码:

#include <boost/asio.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/core.hpp>
#include <string>

using tcp = boost::asio::ip::tcp;               // from <boost/asio/ip/tcp.hpp>
namespace websocket = boost::beast::websocket;  // from <boost/beast/websocket.hpp>

boost::beast::multi_buffer buffer;
boost::asio::io_context ioc_1;
boost::asio::io_context ioc_2;
websocket::stream<tcp::socket> ws_1(ioc_1);
websocket::stream<tcp::socket> ws_2(ioc_2);


void on_write(boost::system::error_code, std::size_t) {
  std::cout << "on_write called" << std::endl << std::flush;
}

void writeFromCounterpart() {
  ws_2.async_write(boost::asio::buffer(std::string("Hello")), on_write);
}

void on_read(boost::system::error_code, std::size_t) {
  std::cout << "on_read called" <<std::endl << std::flush;
}

int main() {
  std::thread t([](){
    auto const address = boost::asio::ip::make_address("127.0.0.1");
    tcp::acceptor acceptor{ioc_2, {address, 30000}};
    tcp::socket socket{ioc_2};

    acceptor.accept(socket);
    websocket::stream<tcp::socket> ws{std::move(socket)};
    ws.accept();
    ws_2 = std::move(ws);
    ioc_2.run();
  });
  t.detach();

  // allow acceptor to accept
  std::this_thread::sleep_for(std::chrono::milliseconds(200));

  tcp::resolver resolver_(ioc_1);
  boost::asio::io_context::strand strand_(ioc_1);
  auto const results = resolver_.resolve("127.0.0.1", "30000");
  boost::asio::connect(ws_1.next_layer(), results.begin(), results.end());
  ws_1.handshake("127.0.0.1", "/");

  ws_1.async_read(buffer, strand_.wrap(on_read));
  strand_.post(writeFromCounterpart);
  auto handlers = ioc_1.run_for(std::chrono::milliseconds(5000));
  std::cout << "Run " + std::to_string(handlers) + " Handlers" << std::endl << std::flush;
}

1 个答案:

答案 0 :(得分:1)

简短的答案是:

它的文档在这里:

  

问题是有时运行此流程时,不会调用on :: read,因此基本上我认为在ws_处于“读取”状态之前调用了SendSomethingOnTheWs。

为什么会这样?流套接字(ws或其他方式)的行为类似于流。如果套接字是 open ,则数据将被缓冲。