在多个线程中使用提升异步 API

using boost async API's with multiple threads

本文关键字:异步 API 线程      更新时间:2023-10-16

关于这篇文章:为什么使用 boost::asio 时每个连接需要链?

我专注于有关异步调用的声明:"但是,多个线程同时进行调用是不安全的"

此示例:http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/example/cpp11/chat/chat_client.cpp

如果我将 main 称为"线程 1",将

生成的线程 t 称为"线程 2",那么线程 1 似乎正在调用async_write(假设没有write_in_progress),而线程 2 正在调用async_read。 我错过了什么?

在官方聊天示例中,chat_client::write()通过 io_service::post() 将工作推迟到io_service,这将:

  • 请求io_service通过当前正在调用poll()poll_one()run()run_one()函数的线程执行给定的处理程序io_service
  • 不允许在调用函数中调用给定的处理程序(例如 chat_client::write()

由于只有一个线程在运行io_service,并且所有套接字读取、写入和关闭操作仅从已发布到io_service的处理程序启动,因此程序满足socket的线程安全要求。

class chat_client
{
  void write(const chat_message& msg)
  {
    // The nullary function `handler` is created, but not invoked within
    // the calling function.  `msg` is captured by value, allowing `handler`
    // to append a valid `msg` object to `write_msgs_`.
    auto handler = [this, msg]()
      {
        bool write_in_progress = !write_msgs_.empty();
        write_msgs_.push_back(msg);
        if (!write_in_progress)
        {
          do_write();
        }
      };
    // Request that `handler` be invoked within the `io_service`.
    io_service_.post(handler);
  }
};