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

问题描述 投票:0回答:1

我的理解是,要结束这个计时器线程,我需要在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.

}
multithreading c++11 boost-asio
1个回答
1
投票

首先,我通常不会打电话给io_service::stop。相反,我将取消所有待处理的工作,并等待服务正常返回。

只有失败了,我才会回到io_service::stop

其次,io_service是少数几个被证明是线程安全的Asio对象之一(除了构造/破坏)。所以你可以从任何地方调用io_service::stop,只要你能确定对象是活着的(没有被破坏)。

© www.soinside.com 2019 - 2024. All rights reserved.