我正在尝试按照示例创建一个多线程服务器 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
函数只会阻塞,直到要加入的线程退出执行,但通常所有线程都会立即开始运行,一旦它们移交了它们可以执行的例程(例如,通过构造函数),不管任何 join
或 detach
调用。
在 asio 的上下文中,当然只有那些线程可以处理调用例如io_service::run
。
关于c++ - Boost asio 无法在所有线程上运行 io 服务。io 服务在第一个线程调用时阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49746304/