我今天一直在“玩”boost threads 作为学习练习,我有一个几个月前构建的工作示例(在我被打断并且不得不放弃多线程一段时间之前) 表现出异常行为。
当我最初编写它时,我使用的是 MingW gcc 3.4.5,它运行良好。现在我使用的是 4.4.0 但它没有 - 顺便说一句,我再次尝试使用 3.4.5(我在安装 4.4.0 时将该版本保存在一个单独的文件夹中)并且它仍在工作。
代码在题末; 总结它所做的是在两个子线程中启动两个 Counter
对象(这些对象简单地增加一个变量然后休眠一会儿并无限重复 - 它们计数),主线程通过 cin.get()
等待用户,然后中断两个线程,等待它们加入,然后输出两个计数器的结果。
符合 3.4.5,它按预期运行。
与 4.4.0 兼容,它一直运行到用户输入为止,然后死掉并显示如下消息 - 似乎中断异常正在杀死整个进程?
terminate called after throwing an instance of ' This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. boost::thread_interrupted'
This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.
根据我的阅读,我认为允许从子线程传播出去的任何(?)未捕获异常都会终止进程?但是,我正在捕捉这里的中断,不是吗?至少我似乎在使用 3.4.5 时是这样。
那么,首先,我了解打扰的工作原理了吗?
并且,关于正在发生的事情以及如何解决的任何建议?
代码:
#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/date_time.hpp>
//fixes a linker error for boost threads in 4.4.0 (not needed for 3.4.5)
//found via Google, so not sure on validity - but does fix the link error.
extern "C" void tss_cleanup_implemented() { }
class CCounter
{
private:
int& numberRef;
int step;
public:
CCounter(int& number,int setStep) : numberRef(number) ,step(setStep) { }
void operator()()
{
try
{
while( true )
{
boost::posix_time::milliseconds pauseTime(50);
numberRef += step;
boost::this_thread::sleep(pauseTime);
}
}
catch( boost::thread_interrupted const& e )
{
return;
}
}
};
int main( int argc , char *argv[] )
{
try
{
std::cout << "Starting counters in secondary threads.\n";
int number0 = 0,
number1 = 0;
CCounter counter0(number0,1);
CCounter counter1(number1,-1);
boost::thread threadObj0(counter0);
boost::thread threadObj1(counter1);
std::cout << "Press enter to stop the counters:\n";
std::cin.get();
threadObj0.interrupt();
threadObj1.interrupt();
threadObj0.join();
threadObj1.join();
std::cout << "Counter stopped. Values:\n"
<< number0 << '\n'
<< number1 << '\n';
}
catch( boost::thread_interrupted& e )
{
std::cout << "\nThread Interrupted Exception caught.\n";
}
catch( std::exception& e )
{
std::cout << "\nstd::exception thrown.\n";
}
catch(...)
{
std::cout << "\nUnexpected exception thrown.\n"
}
return EXIT_SUCCESS;
}
最佳答案
已解决。
事实证明,添加编译器标志 -static-libgcc
消除了 4.4.0 的问题(并且对 3.4.5 没有明显影响)——或者至少在这种情况下程序返回预期结果。
关于c++ - 使用 MinGW gcc 4.4.0 boost thread_interrupted 异常终止(),3.4.5 OK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3189306/