c++ - 带线程的异步方法

标签 c++ multithreading boost asynchronous boost-asio

我有一个方法可以为新连接启动一个新的 std::thread,这样我就可以读取数据和做其他事情。 线程调用的方法以异步方式(使用 boost 函数)运行读取,并在调用 async_read_some 后返回,我的问题是:

哪个线程处理回调?调用 async_read_some 的线程是同一个线程,还是那个线程在调用它并返回后死了,现在主线程正在处理读取?

这是一个代码片段:

    connection::connection_thread = std::thread(&connection::read_header,
                                                 this);
    connection::connection_thread.detach();
               .
               .
               .
  void connection::read_header() {
    socket_.async_read_some(boost::asio::buffer(headbuf_),
      strand_.wrap(
        boost::bind(&connection::on_header_read, shared_from_this(),
          boost::asio::placeholders::error,
          boost::asio::placeholders::bytes_transferred)));
    begin_timeout();
  }

最佳答案

What thread handles the call-back?

轮询或运行关联的 io_service 的线程(或线程之一,如果有多个线程) .处理程序传递给服务以在完成时调用。

Is is the same thread that made the call to the async_read_some

不,async 函数从不直接调用处理程序;它总是由 io_service 调用,即使操作立即完成也是如此。

or did that thread die after it called it and returned and now the main thread is handling the reads?

这完全取决于您如何管理线程。如果您不再需要调用 async 的线程,它可能会死掉;您将需要一些其他线程(可能是主线程,也可能是其他线程)来处理 io_service 并完成异步操作。

但是,启动线程来启动异步操作没有意义,因为它会立即完成。将对 async_read_some 的调用移动到您当前启动线程的位置;或使用线程执行同步 操作。如果您选择多线程同步设计,则不需要线程来轮询 io_service 以进行异步操作。

关于c++ - 带线程的异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18724487/

相关文章:

c++ - 将文本标记为类型、字符串对

c++ - 强制 boost 使用 POSIX 共享内存而不是 System V?

c++ - C++ MS Visual Studio错误 “referenced in function public: void __thiscall …”

c++ - 使用对象生命周期运行线程

java - 多线程应用程序中的静态计数器线程是否安全?

python - 客户端没有响应 - Python 中的多线程

c++ - 在编译时计算一个小整数的阶乘

c++ - Clang 问题 : implicit type conversion at construction time

c++ - 如何让部分模板与子类一起使用

c++ - 如何在 C++ 中将 SQLCHAR 转换为字符串