【问题标题】:using boost async API's with multiple threads使用多线程的 boost 异步 API
【发布时间】:2016-10-13 09:04:31
【问题描述】:

关于这篇文章: 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。我错过了什么?

【问题讨论】:

  • 可能 io_service 线程 (t) 不受此规则约束。

标签: c++ multithreading boost boost-asio


【解决方案1】:

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

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

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

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);
  }
};

【讨论】:

  • 有趣。 io_service::post 绝对是我正在查看的聊天示例 (v1.55) 和最新的聊天示例 (v1.61) 之间的区别。因此,似乎有人注意到了与我完全相同的事情并修复了它。从现在开始,我会坚持使用最新版本。
  • @Chris 也许这个例子不是官方的例子? io_service.post1.55 C++11 chat client 中,并且自从 Asio 被 Boost 接受后就在示例中使用(参见 1.35 chat example)。
  • 我的链接指向 boost.org...据我所知这是官方的。它在谷歌搜索中也显示得很高,但我不记得我到底搜索了什么。也许您说该文件存在于他们的服务器上,但不是 1.55 官方文档的一部分。可能。它不像我在其他 boost.org 文档中看到的那样,在页面的右下方没有“主页”和箭头按钮。如果您查看我链接的页面...缺少 io_service::post,然后单击顶部的链接将您带到“此页面的最新版本”并显示 io_service::post。奇数。
  • 好吧,现在 io_service::post 出现在我的链接中。我放弃。我告诉你这是伏都教。
猜你喜欢
  • 1970-01-01
  • 2012-09-08
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 2021-07-15
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多