boost :: thread interrupt()仅在第一次执行中断点时抛出异常?我的情况如下。
我创建了一个boost::thread
来执行functionA.
functionA
次来电functionB
,当我functionB
时,我们调用了threadInterrupt.
functionB
抛出boost::thread_interrupted
异常并返回functionA.
我的问题是,当执行另一个中断点时,是否会在functionA中抛出新的boost::thread_interrupted
异常。
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;
}
}
答案 0 :(得分:1)
你试过吗?见 Live On 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
如您所见,中断请求的行为类似于一种自动重置标志。