使用具有多个线程的boost async API

时间:2016-06-13 03:23:19

标签: c++ multithreading boost boost-asio

关于这篇文章: Why do I need strand per connection when using 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”,那么当线程2调用async_read时,似乎线程1正在调用async_write(假设没有write_in_progress)。我错过了什么?

1 个答案:

答案 0 :(得分:1)

在官方chat example中,chat_client::write()将工作推迟到io_service通过io_service::post(),这将:

  • 请求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);
  }
};