有一个使用 boost::asio 的例子。
- 为什么这个例子使用 boost::asio::io_service::work ?
- 为什么
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::work 的情况下使用 io_service 时,poll 和 run 有什么区别?
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;
}