Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top