问题描述
我想使用boost ::线程中断中断线程()。我有以下的code不抛出抛出boost :: thread_interrupted&安培;例外:
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;
}
如果我更换的boost :: this_thread :: interruption_point()用的boost :: this_thread ::睡眠(升压::了posix_time ::毫秒(150))的例外是罚球和中断的作品,因为它应该。
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.
有人能解释为什么提振:: this_thread :: interruption_point()不会抛出预期的异常?
Can someone explain why boost::this_thread::interruption_point() doesn't throw the expected exception?
推荐答案
作为评论者指出,有没有办法排除一个简单的竞争条件(取决于你的架构和负载了很多CPU上)。增加一个明确的睡眠帮助其实凸显了这一。
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) << "\n";
}
int main()
{
boost::thread t(treadf);
//t.interrupt(); // UNCOMMENT THIS LINE
t.join();
}
它打印
Returned: 20000
或者,如果你用注释 t.interrupt行()
interrupted
Returned: 0
在我的i7处理器的系统。看到它的
On my i7 system. See it Live On Coliru
这篇关于提高:: this_thread :: interruption_point()不会抛出抛出boost :: thread_interrupted&安培;例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!