c++ - Boost asio 无法在所有线程上运行 io 服务。io 服务在第一个线程调用时阻塞

标签 c++ multithreading boost boost-asio boost-thread

我正在尝试按照示例创建一个多线程服务器 HTTP Server 3 .我已按照示例所示进行操作。

用于创建线程的服务器代码。 版本 1

for (std::size_t i = 0; i < thread_pool_size_; ++i) {
    boost::shared_ptr<boost::thread> thread(new boost::thread(boost::bind(&boost::asio::io_service::run, &ios_)));
    threads_.push_back(thread);
  }
  for (std::size_t i = 0; i < threads_.size(); ++i){
        LOGV << "performing join operation for thread = "<< i;
    threads_[i]->join();
  }

版本 2

for (std::size_t i = 0; i < thread_pool_size_; ++i) {
  boost::shared_ptr<boost::thread> thread(new boost::thread(
    [this](){ LOGV << "Intiating thread"; this->ios_.run(); }));
    threads_.push_back(thread);
  }
  for (std::size_t i = 0; i < threads_.size(); ++i){
        LOGV << "performing join operation for thread = "<< i;
    threads_[i]->join();
  }

版本 1 给我输出:

performing join operation for thread = 0

版本 2 为我提供了 10 个线程的以下输出。

[Tcp::Server::run@76] Initiating threads Initiating thread
Initiating thread
Initiating thread
Initiating thread
Initiating thread
Initiating thread
Initiating thread
Initiating thread
performing join operation for thread = 0
Initiating thread
Initiating thread

我想了解是使用了所有线程,还是只使用了一个执行join操作的线程。有人可以解释我哪里出错了,并建议是否有任何好的方法来做到这一点,我也以与​​建议的示例相同的方式使用 strand。

提前致谢

最佳答案

I want to understand wether all threads are used, or only one thread that executed join operation is used..

前者。 join 函数只会阻塞,直到要加入的线程退出执行,但通常所有线程都会立即开始运行,一旦它们移交了它们可以执行的例程(例如,通过构造函数),不管任何 joindetach 调用。

在 asio 的上下文中,当然只有那些线程可以处理调用例如io_service::run

关于c++ - Boost asio 无法在所有线程上运行 io 服务。io 服务在第一个线程调用时阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49746304/

相关文章:

java - 运行多线程的问题

c++ - Qt moveToThread,带参数的信号/槽

c++ - 不从派生类调用基类构造函数

c++ - 为 MyVector 创建一个 push_back() 函数

multithreading - 暂停线程的执行而不休眠?

c++ - 有人可以解释 Mutex 及其使用方法吗?

c++ - 使用boost math的编译问题

c++ - 用于 boost 多索引容器的模板参数

visual-c++ - 如何使用Visual Studio 2010在Windows上编译G++

c++ - 猜测模板中的矩阵类型