[英]ThreadPool with boost::asio does not quit?
I have the following minmal example of a thread pool made with boost::asio. 我有一个用boost :: asio制成的线程池的最小示例。
#include <queue>
#include <map>
#include <boost/shared_ptr.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/thread/thread.hpp>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp> // remove me (only for io)
class ThreadPool
{
public:
void work_as_mainthread(void) { m_io_service.run(); }
ThreadPool(int poolSize = 4) : timer(m_io_service)
{
timer.expires_from_now(boost::posix_time::seconds(1)); // this line does not affect the problem
m_pWork.reset( new boost::asio::io_service::work(m_io_service) );
for ( int i = 0; i < poolSize; ++i)
m_threadGroup.create_thread( boost::bind(&boost::asio::io_service::run, &m_io_service) );
}
~ThreadPool()
{
m_pWork.reset();
m_threadGroup.join_all();
}
private:
boost::asio::io_service m_io_service;
boost::asio::deadline_timer timer;
boost::shared_ptr<boost::asio::io_service::work> m_pWork;
boost::thread_group m_threadGroup;
};
int main()
{
int n_threads = 2;
ThreadPool pool(n_threads);
pool.work_as_mainthread();
// this line is never reached...
return 0;
}
If you like, you can compile it like this: 如果愿意,可以这样编译:
g++ -Wall -g -lboost_thread -lboost_date_time -lboost_system main.cpp -o main
What makes me wonder is that the program does not stop. 让我感到奇怪的是该程序没有停止。 What I do is calling io_service::run, but without any "work" for it.
我所做的是调用io_service :: run,但没有任何“工作”。 io_services without work quit themselves, as said in the boost::asio docs.
如boost :: asio docs中所述,没有工作的io_services自行退出。 Now, why does my program never quit?
现在,为什么我的程序永不退出?
When you create a boost::asio::io_service::work
object, that keeps the io_service
from completing. 当您创建
boost::asio::io_service::work
对象时,将使io_service
无法完成。
// This line keeps the io_service running
m_pWork.reset( new boost::asio::io_service::work(m_io_service) );
If you want it to stop, you would need to destroy that work object, like this: 如果要使其停止,则需要销毁该工作对象,如下所示:
// stop the worker(s)
m_pWork.reset();
It's up to you to find an appropriate time/place to do this. 由您自己决定合适的时间/地点。 I would suggest calling
timer.async_wait()
, then in the handler you can reset your work object to see how this all should be working together. 我建议您调用
timer.async_wait()
,然后在处理程序中重置您的工作对象,以查看所有这些如何协同工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.