Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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) << "
";
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...