【发布时间】:2014-09-29 15:38:55
【问题描述】:
我想使用 boost::thread interrupt() 来中断一个线程。我有以下代码不会抛出 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;
}
如果我将 boost::this_thread::interruption_point() 替换为 boost::this_thread::sleep( boost::posix_time::milliseconds(150)) 会抛出异常并且中断正常工作。
谁能解释为什么 boost::this_thread::interruption_point() 没有抛出预期的异常?
【问题讨论】:
-
很可能使用 boost::this_thread::interruption_point() 在 boost::thread::interrupt() 调用之前已经退出循环。 boost::this_thread::interruption_point() 不会在任何时候阻塞,它只是一个线程可以被中断的检查点,并且 20000 不是检查此类内容的非常高的迭代次数,除非其他代码未显示需要相当长的时间才能完成。
-
您好,感谢您的回复。当 boost::thread::interrupt() 被调用时,我仍在循环中,因为我正在打印计数器并且它还没有达到 20000。 boost::this_thread::interruption_point(); 之后的代码很长并且需要时间来完成这就是为什么我需要在某些情况下打断它。
-
我现在意识到你不能在一个不返回的函数之前放置一个 interrupt_point 并期望中断来停止它。一旦调用了interrupt,下次再运行interrupt_point,就会抛出异常,对吗?
-
函数返回,我的错误没有包含在提供的代码中。
标签: c++ boost interrupted-exception