【发布时间】:2018-09-19 15:22:38
【问题描述】:
我正在尝试按照示例创建多线程服务器 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 给了我输出:
执行线程 = 0 的连接操作
版本 2 为我提供了以下 10 个线程的输出。
[Tcp::Server::run@76] 启动线程 启动线程
启动线程
启动线程
启动线程
启动线程
启动线程
启动线程
启动线程
为 thread = 0 执行连接操作
启动线程
启动线程
我想了解是使用了所有线程,还是只使用了一个执行连接操作的线程。有人可以解释我哪里出错并建议是否有任何好的方法可以做到这一点,我也以与示例建议相同的方式使用 strand。
提前致谢
【问题讨论】:
-
对 io_service::run 的调用是否完成?如果 io_service 中有未完成的工作,则不会,除非调用 io_service::stop()。这是设计使然。
标签: c++ multithreading boost boost-asio boost-thread