C++ boost::this_thread::interruption_point()不';t抛出增压::线程被中断&;例外

C++ boost::this_thread::interruption_point()不';t抛出增压::线程被中断&;例外,c++,boost,interrupted-exception,C++,Boost,Interrupted Exception,我想使用boost::thread interrupt()中断线程。我有以下代码不会抛出boost::thread\u interrupted&exception: int myClass::myFunction (arg1, arg2) try{ //some code here do { boost::this_thread::interruption_point(); //some other code here } while (c

我想使用boost::thread interrupt()中断线程。我有以下代码不会抛出boost::thread\u interrupted&exception:

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;
}
int myClass::myFunction(arg1、arg2)试试看{
//这里有一些代码
做{
boost::this_thread::interruption_point();
//这里还有其他代码
}而(计数器!=20000);
}捕获(boost::线程中断&){

cout正如评论者所指出的,没有办法排除简单的竞争条件(很大程度上取决于您的体系结构和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();
}
或者,如果使用
t.interrupt()取消对行的注释


在我的i7系统上。请参见

很可能在boost::this_thread::interrupt_point()调用之前,您已经退出了循环。boost::this_thread::interrupt_point()调用任何时候都不会阻塞,它只是一个检查点,线程可以在这里被中断,20000不是一个很高的检查次数,除非其他未显示的代码需要相当长的时间才能完成。您好,感谢您的回复。当boost::thread::interrupt()时被称为“我仍在循环中”,因为我正在打印计数器,但它还没有达到20000;很长,需要时间才能完成这就是为什么在某些情况下我需要中断它。我现在意识到,您不能将中断点放在不返回的函数之前,并期望中断停止它。一旦调用中断,下一次运行中断点时,会抛出异常,对吗?函数返回,我的错误不是我请将其包含在提供的代码中。您好,谢谢您的回复。我运行的是双核系统。我阅读了您提供的示例,但我看不出这与我的代码有什么区别。我想您可以发布一个SSCCE,为您说明问题。也许我们可以发现一些东西
Returned: 20000
interrupted
Returned: 0