简体   繁体   English

boost :: this_thread :: interruption_point()不会引发boost :: thread_interrupted&异常

[英]boost::this_thread::interruption_point() doesn't throw boost::thread_interrupted& exception

I want to interrupt a thread using boost::thread interrupt(). 我想使用boost :: thread interrupt()中断线程。 I have the following code which doesn't throw boost::thread_interrupted& exception: 我有以下代码不会引发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;
}

If I replace boost::this_thread::interruption_point() with boost::this_thread::sleep( boost::posix_time::milliseconds(150)) exception is throw and interrupt works as it should. 如果我将boost :: this_thread :: interruption_point()替换为boost :: this_thread :: sleep(boost :: posix_time :: milliseconds(150)),则会引发异常,并且中断应按预期进行。

Can someone explain why boost::this_thread::interruption_point() doesn't throw the expected exception? 有人可以解释为什么boost :: this_thread :: interruption_point()没有引发预期的异常吗?

As the commenter noted, there's no way to rule out a simple race condition (depends a lot on your architecture and load on the CPU). 正如评论者所指出的,无法排除简单的竞争条件(这在很大程度上取决于您的体系结构和CPU的负载)。 The fact adding an explicit sleep "helps" underlines this. 添加显式睡眠的事实“有所帮助”突显了这一点。

Are you running on a single-core system? 您是否在单核系统上运行?

Here's a simple selfcontained example in case you spot something you are doing differently. 这是一个简单的独立示例,以防您发现自己做的事情有所不同。 See this simple tester: 看到这个简单的测试器:

#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();
}

It prints 它打印

Returned: 20000

Or, if you uncomment the line with t.interrupt() 或者,如果您用t.interrupt()取消注释该行

interrupted
Returned: 0

On my i7 system. 在我的i7系统上。 See it Live On Coliru 在Coliru上实时观看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM