我想使用boost::线程中断()来中断线程。我有以下代码,它不会引发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()不抛出预期的异常吗?
发布于 2014-09-29 16:11:13
正如评论者所指出的,没有办法排除简单的竞争条件(这在很大程度上取决于您的体系结构和CPU上的负载)。添加显式睡眠的事实“有助于”强调这一点。
您是在单核系统上运行吗?
这里有一个简单的自包含的例子,以防你发现你正在做的事情不同。请参阅这个简单的测试器:
#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();
}印出来
Returned: 20000或者,如果用t.interrupt()取消注释行
interrupted
Returned: 0在我的i7系统上。看吧,Live On Coliru
https://stackoverflow.com/questions/26103648
复制相似问题