我有以下使用 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 会自行退出。现在,为什么我的程序永远不会退出?