关于asio中的io_service::run函数在没有任务时退出的问题

时间:2021-06-30 10:56:36

io_service::run函数在没有任何任务的时候将会自动返回,这对于WTL的项目来说并不方便,之前我有一篇文章讲到使用一个循环来运行该run函数,那是十分不优雅的。今天在网上再次查找办法,终于找到io_service::work类可以使io_service::run函数在没有任务的时候仍然不返回,直至work对象被销毁。

boost::asio::io_service ios;
boost::asio::io_service::work work(ios); // 使用work对象
ios.run(); // 就算是当前没有任务,ios.run()也不会马上返回


或者,下面从我的程序中直接拷贝出来的例子,该程序使用WTL框架

boost::asio::io_service m_ios;
std::shared_ptr<boost::thread> m_ios_thread;
std::shared_ptr<tm_client> m_client_ptr;
std::shared_ptr<boost::asio::io_service::work> m_work;

m_work.reset(new boost::asio::io_service::work(m_ios));
m_ios_thread.reset(new boost::thread(boost::bind(&boost::asio::io_service::run, &m_ios)));

// resolve the hostname
boost::asio::ip::tcp::resolver resolver(m_ios);
boost::asio::ip::tcp::resolver::query q(hostname, boost::lexical_cast<std::string>(x::tl::PORT_TMSRV));
boost::asio::ip::tcp::resolver::iterator res_begin = resolver.resolve(q), res_end;

if (res_begin != res_end)
{
// constructor client connection object
m_client_ptr.reset(new tm_client(m_ios, tm_window_notifier(*this)));
m_client_ptr->connect(*res_begin);
}


另外可以参考文章:Stopping the io_service from running out of work


From: http://btblog.net/?p=50