我有以下使用 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;
}
如果你喜欢,你可以这样编译:
g++ -Wall -g -lboost_thread -lboost_date_time -lboost_system main.cpp -o main
令我奇怪的是程序并没有停止。我所做的是调用 io_service::run,但没有任何“工作”。如 boost::asio 文档中所述,没有工作的 io_services 会自行退出。现在,为什么我的程序永远不会退出?
最佳答案
当您创建一个 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) );
如果你想让它停止,你需要销毁那个工作对象,像这样:
// stop the worker(s)
m_pWork.reset();
这取决于您找到合适的时间/地点来执行此操作。我建议调用 timer.async_wait()
,然后在处理程序中您可以重置您的工作对象以查看这一切应该如何协同工作。
参见 this文档的一部分。
关于c++ - 带有 boost::asio 的 ThreadPool 不退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12095258/