KoK*_*oKa 2 c++ boost interrupted-exception
我想使用boost :: thread interrupt()中断一个线程.我有以下代码,不会抛出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;
}
Run Code Online (Sandbox Code Playgroud)
如果我用boost :: this_thread :: sleep(boost :: posix_time :: milliseconds(150))替换boost :: this_thread :: interruption_point(),则抛出异常并且中断按预期工作.
有人可以解释为什么boost :: this_thread :: interruption_point()不会抛出预期的异常?
正如评论者指出的那样,没有办法排除简单的竞争条件(很大程度上取决于您的架构和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();
}
Run Code Online (Sandbox Code Playgroud)
它打印
Returned: 20000
Run Code Online (Sandbox Code Playgroud)
或者,如果您取消注释该行 t.interrupt()
interrupted
Returned: 0
Run Code Online (Sandbox Code Playgroud)
在我的i7系统上.看到Live On Coliru
归档时间: |
|
查看次数: |
4660 次 |
最近记录: |