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

懵懂的女人 提交于 2019-11-30 09:33:57

问题


I want to interrupt a thread using boost::thread interrupt(). I have the following code which doesn't throw boost::thread_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;
}

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.

Can someone explain why boost::this_thread::interruption_point() doesn't throw the expected exception?


回答1:


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). 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()

interrupted
Returned: 0

On my i7 system. See it Live On Coliru



来源:https://stackoverflow.com/questions/26103648/boostthis-threadinterruption-point-doesnt-throw-boostthread-interrupted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!