1

boost::thread interrupt() 仅在第一次执行中断点时引发异常?我的情况如下。

我创建了一个boost::thread执行functionA. functionA调用的函数functionB,当functionB我们调用函数时threadInterrupt. functionB会抛出boost::thread_interrupted异常并返回functionA.我的问题是boost::thread_interrupted,当另一个中断点被执行时,是否会在函数 A 中抛出一个新的异常。

void MyClass::function(int arg1, int arg2) try {
    boost::thread* t = new boost::thread(boost::bind(&MyClass::functionA, this, var1, var2));
} catch (...) {
    cout << "function throw an exception" << endl;
}

void MyClass::functionA(int arg1, int arg2 ) try {
    //some code here
    try {
        int retVal = MyClass::functionB(var);
        boost::this_thread::interruption_point();
        //some code here
    } catch(boost::thread_interrupted&) {
        cout << "thread interrupted in functionA" << endl;
    }
} catch (...) {
    cout << "functionA throw an exception" << endl;
}

int MyClass::functionB(int arg1) try {
    //some code here
    try {
        boost::this_thread::interruption_point();
        //some code here
    } catch(boost::thread_interrupted&) {
        cout << "thread interrupted in functionB" << endl;
        return 0;
    }
    return 1;
} catch (...) {
    cout << "functionB throw an exception" << endl;
    return 1;
}

void MyClass::threadInterrupt() {
    if (thr!=NULL) {
        thr->interrupt();
        thr->join();
        delete thr;
        thr=NULL;
    }
}
4

1 回答 1

1

你试过了吗?在Coliru现场观看

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

using namespace boost;

int main() {
    thread t([]{
            int i = 0;
            while (true) try {
                if (i >= 10) return;
                while (i < 10) {
                    this_thread::sleep_for(chrono::milliseconds(200));
                    std::cout << "processed " << i++ << "\n";
                }
            }
            catch (...) { std::cout << "Interrupted at i = " << i << "\n"; }
    });

    this_thread::sleep_for(chrono::milliseconds(800));
    t.interrupt();

    t.join();
    std::cout << "Interrupt requested? : " << std::boolalpha << t.interruption_requested() << "\n";
}

输出:

processed 0
processed 1
processed 2
Interrupted at i = 3
processed 3
processed 4
processed 5
processed 6
processed 7
processed 8
processed 9
Interrupt requested? : false

如您所见,中断请求的行为类似于一种自动复位标志。

于 2014-10-03T08:15:51.407 回答