boost::this_thread::interruption_point()不会抛出boost::thread_interrupted&异常。

3

我想使用boost::thread interrupt()中断一个线程。我有以下代码,但它并不抛出boost::thread_interrupted&异常:

int myClass::myFunction (arg1, arg2) try{
//some code here
    do {   
        boost::this_thread::interruption_point(); 
        //some other code here
    } while (counter != 20000); 
}catch (boost::thread_interrupted&) {
    cout << "interrupted" << endl;
}

如果我将boost :: this_thread :: interruption_point()替换为boost :: this_thread :: sleep(boost :: posix_time :: milliseconds(150)),那么异常将被抛出,并且中断将起作用。

有人能解释一下为什么boost :: this_thread :: interruption_point()没有引发预期的异常吗?


1
很有可能在boost::thread::interrupt()调用之前,您已经通过boost::this_thread::interruption_point()退出了循环。boost::this_thread::interruption_point()不会阻塞任何时间,它只是一个检查点,在这里线程可以被中断,而20000并不是一个非常高的迭代次数来检查这样的事情,除非未显示的其他代码需要相当长的时间才能完成。 - diverscuba23
嗨,感谢回复。当调用boost :: thread :: interrupt()时,我仍然在循环内部,因为我正在打印计数器,并且它还没有达到20000。 boost :: this_thread :: interruption_point()之后的代码很长,需要时间才能完成,这就是为什么我需要在某些情况下中断它的原因。 - KoKa
我现在意识到,在一个不返回的函数之前放置一个中断点,并期望中断停止它是不可能的。一旦调用中断,下一次运行中断点时,异常就会被抛出,对吗? - xinthose
1
函数返回,我的错误是没有在提供的代码中包含它。 - KoKa
1个回答

5

正如评论者所指出的,无法排除简单的竞态条件(这在很大程度上取决于您的架构和CPU负载)。 明确添加睡眠“有所帮助”这一事实强调了这一点。

您是否在单核系统上运行?

如果您发现自己有所不同,请参考此简单的自包含示例。 请查看此简单测试程序:

#include <iostream> 
#include <boost/thread.hpp>

struct myClass { 
    int myFunction(int arg1, int arg2);
};

int myClass::myFunction (int arg1, int arg2)
{
    int counter = 0;
    try
    {
        //some code here
        do {   
            boost::this_thread::interruption_point(); 
            //some other code here
            ++counter;
        } while (counter != 20000); 
    } catch (boost::thread_interrupted&) {
        std::cout << "interrupted" << std::endl;
    }
    return counter;
}

void treadf() {
    myClass x;
    std::cout << "Returned: " << x.myFunction(1,2) << "\n";
}

int main()
{
    boost::thread t(treadf);
    //t.interrupt(); // UNCOMMENT THIS LINE
    t.join();
}

它打印

Returned: 20000

或者,如果您取消注释带有 t.interrupt() 的行
interrupted
Returned: 0

在我的i7系统上。在这里查看它的实时效果:在Coliru上实时查看

嗨,感谢您的回复。我正在双核系统上运行。我阅读了您提供的示例,但我无法发现它与我的代码之间的任何区别。 - KoKa
我想你可以发布一个 SSCCE 来展示你遇到的问题。也许我们能够发现一些东西。 - sehe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接