如何在 C++ 中中断 boost::this_thread

How to interrupt boost::this_thread in c++

在我的应用程序中,我给了 10 秒的睡眠时间。我已经使用 boost::this_thread::sleep 函数进行睡眠。 有没有可能中断 boost::this_thread::sleep 功能的方法?

您可以使用 interrupt() 中断 sleep 函数。

你必须为你的线程开启中断,当它休眠时,你可以使用中断功能。

Boost 有一个关于此的非常好的在线简短教程,请看这里:http://www.boost.org/doc/libs/1_54_0/doc/html/thread/thread_management.html#thread.thread_management.tutorial.interruption

来自sleep() reference:

Throws: boost::thread_interrupted if the current thread of execution is interrupted.

Notes: sleep() is one of the predefined interruption points.

所以您需要在您的线程中做的是将 sleep() 调用放入 try-catch,然后捕获 boost::thread_interrupted。然后在线程对象上调用 interrupt() 来中断睡眠。


对了,也来自sleep reference:

Warning

DEPRECATED since 3.0.0.

Use sleep_for() and sleep_until() instead.

I have given sleep using boost::this_thread::sleep function. Is there any possible way to interrupt boost::this_thread::sleep function.?

不是这样,但实现起来并不难,boost::this_thread::sleep:

void sleep_for(boost::posix_time::milliseconds interval, std::atomic<bool>& interrupted)
{
    static const auto resolution = boost::posix_time::milliseconds(10));
    ptime end_time(microsec_clock::local_time()) + interval;

    while( !interrupted.load() )
    {
        boost::this_thread::sleep(resolution);
        if(microsec_clock::local_time() > end_time)
            break;
    }
}

客户端代码线程 1:

std::atomic<bool>& interrupt = false;

void f() {
    sleep_for(boost::posix_time::milliseconds(200), interrupt);
}

客户端代码线程 2:

interrupt.store(true); /// will cause thread 1 to be interrupted, if called
                       /// during execution of sleep_for.