c++ - 将 boost async API 与多个线程一起使用

标签 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”,那么看起来线程 1 正在调用 async_write(假设没有 write_in_progress),而线程 2 正在调用 async_read。我错过了什么?

最佳答案

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

  • 请求 io_service 通过当前正在调用 poll() 的线程执行给定的处理程序,poll_one()run(),或 io_service
  • 上的 run_one() 函数
  • 不允许在调用函数中调用给定的处理程序(例如 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);
  }
};

关于c++ - 将 boost async API 与多个线程一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37781385/

相关文章:

c++ - 突然崩溃后,程序中的所有指针变量都被删除了吗?

c++ - (词袋)中的段错误

c++ - Boost几何cartesian2d.hpp

c++ - 如何使用 unique_ptr 执行 dynamic_cast?

c++ - BOOST_PP_REPEAT 中数据的多个参数

C++:静态分析代码(和/或预处理代码)的工具

c++ - 在彼此非常接近的范围内混合二进制数据和指令是否有缓存惩罚?

mysql - Ruby 中的并行 mysql I/O

ios - UIFont线程安全吗?

c++ - Boost:创建对象并使用线程填充 vector