如何取消线程中的 io_service 对象?

How to cancel io_service object in a thread?

我的理解是,要结束这个计时器线程,我需要在 io_service 对象上调用 stop() 。我这样做是为了 MyClass 对象(也 运行 作为线程)在线程结束时不会以活动异常结束。

如何使用 lambda 在标准线程中取消 io_service 对象?

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.

}

首先,我通常不会打电话给io_service::stop。相反,我会取消所有未完成的工作并等待服务正常 return.

只有在失败时我才会回退到io_service::stop

其次,io_service 是少数被记录为线程安全的 Asio 对象之一(construction/destruction 除外)。所以你可以从任何地方调用 io_service::stop,只要你能确定对象是活的(没有被破坏)。