boost::asio hangs in resolver service destructor after throwing out of io_service::run()

前提是你 提交于 2020-01-01 19:08:33

问题


I'm using a fairly simple boost::asio set-up, where I call io_service.run() from the main thread. I have a tcp resolver, and use async resolve to look up an address. When that look-up fails, I throw an exception inside the asynchronous callback. I catch this exception outside the run() call, inside the main function. I then call stop() on my io_service instance (which is a global). However, when main() returns, the program hangs. It turns out to be waiting for an exit_event_ that never comes from the resolver service.

I do not wish to hang on exit. Is there something I'm doing wrong? If so, what? I haven't found much discussion about these things online. I'm using boost 1.41.0 on Windows 7/64bit.


回答1:


I then call stop() on my io_service

Try to use this trick (copied from io_service documentation) when you need to stop io_service:

boost::asio::io_service io_service;
auto_ptr<boost::asio::io_service::work> work(
    new boost::asio::io_service::work(io_service));
...
work.reset(); // Allow run() to exit. 

The reason is simple (also from the documentation): call to io_service::stop() will cause the io_service run() call to return as soon as possible, abandoning unfinished operations and without permitting ready handlers to be dispatched.

So, calling io_service::stop() is not enough if you need to dispatch all handlers.




回答2:


stop() just signals the io_service to stop. If you follow the stop() call with another run() call it should return and clean up properly.

There is some discussion about throwing exceptions from handlers in the documentation.

I'm also guessing the issue may be related to some object lifetime issue, e.g. the io service is destroyed while something else is still referencing it. Take a closer look at the examples and how shared pointers are used to ensure the objects are still around.



来源:https://stackoverflow.com/questions/3324293/boostasio-hangs-in-resolver-service-destructor-after-throwing-out-of-io-servic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!