Ender
Ender

Reputation: 1778

How to cancel io_service object in a thread?

My understanding is that to end this timer thread, I need to call stop() on the io_service object. I'm doing this so that the MyClass object (also running as a thread) doesn't end in an active exception when it's thread ends.

How does one cancel an io_service object in a standard thread using a lambda?

class MyClass
{
    private:
        boost::asio::io_service io;

    // ...
}

void MyClass::operator()()
{
    boost::asio::deadline_timer my_timer(io,
        boost::posix_time::seconds(300));

    my_timer.async_wait(boost::bind(&MyTest::pump, this,
        boost::asio::placeholders::error, &my_timer));

    std::unique_ptr<std::thread> io_thread(
        std::make_unique<std::thread>([&] { io.run(); }));


    // ...

    // cancel here.

}

Upvotes: 0

Views: 141

Answers (1)

sehe
sehe

Reputation: 392843

First of all, I wouldn't usually call io_service::stop. Instead I'd cancel all pending work and wait for the service to gracefully return.

Only if that fails I'll fall back to io_service::stop.

Secondly, the io_service is one of the few Asio objects that's documented to be thread-safe (except for construction/destruction). So you can just call io_service::stop from anywhere, as long as you can be sure the object is alive (not destructed).

Upvotes: 1

Related Questions