这里有一个使用boost::asio的例子。
1.为什么这个例子使用boost::asio::io_service::work?
1.为什么不调用srv.run ();
来执行线程中的任务?
int main()
{
boost::asio::io_service srv;
boost::asio::io_service::work work(srv);
boost::thread_group thr_grp;
thr_grp.create_thread(boost::bind(&boost::asio::io_service::run, &srv));
thr_grp.create_thread(boost::bind(&boost::asio::io_service::run, &srv));
srv.post(boost::bind(f1, 123));
srv.post(boost::bind(f1, 321));
//sync
srv.post(boost::bind(f2, 456));
srv.post(boost::bind(f2, 654));
//sync
srv.stop();
thr_grp.join();
}
**更新:**使用io_service而不使用io_service::work时,轮询和运行有什么区别?
int main()
{
boost::asio::io_service srv;
//boost::asio::io_service::work work(srv);
std::vector<boost::thread> thr_grp;
srv.post(boost::bind(f1, 123));
srv.post(boost::bind(f1, 321));
//sync
srv.post(boost::bind(f2, 456));
srv.post(boost::bind(f2, 654));
//sync
// What is the difference between the poll and run, when io_service without work?
thr_grp.emplace_back(boost::bind(&boost::asio::io_service::poll, &srv));// poll or run?
thr_grp.emplace_back(boost::bind(&boost::asio::io_service::run, &srv));// poll or run?
srv.stop();
for(auto &i : thr_grp) i.join();
int b;
std::cin >> b;
return 0;
}
2条答案
按热度按时间r9f1avp51#
当
io_service::run
方法在没有工作对象的情况下被调用时,它将立即返回。通常,这不是大多数开发人员正在寻找的行为。当然也有一些例外,但大多数开发人员都希望指定一个线程来处理所有的异步处理,并且不希望该线程在被告知退出之前退出。这就是你的代码示例所做的。io_service::run
方法被指定为create_thread方法中的委托或函数指针。因此,当线程从create_thread
方法创建时,它将调用io_service::run
方法,并传递io_service
对象作为参数。通常,一个io_service
对象可以与多个套接字对象一起使用。stop方法通常在关闭应用程序或不再需要所有客户端/服务器之间的通信时调用,并且预计不需要启动任何新的连接。
n3ipq98p2#
work用于通知io_context工作何时开始和完成。Boost文档说,那是弃用的。