[英]boost::thread program crashes on throwing std::exception
I am puzzled as to why this program crashes. 我很困惑为什么这个程序崩溃了。 This is the entire program 这是整个计划
#include<fstream>
#include<string>
#include<iostream>
#include <exception>
#include <boost/thread/thread.hpp>
void func( const std::string& filename )
{
std::ofstream outFile( filename.c_str(), std::ios::binary);
if( !outFile.is_open() )
{
std::string err("Could not open file ");
err.append(filename);
err.append(" for writing");
throw std::exception(err.c_str());
}
}
int main()
{
std::string filename("xX:\\does_not_exist.txt");
try
{
boost::thread thrd(boost::bind(&func, filename ));
thrd.join();
// func( filename ); // calling this does not cause a crash
}
catch( const std::exception& ex)
{
std::cout << ex.what() << std::endl;
}
return 0;
}
Environment 环境
Windows 7 Windows 7的
Visual Studio Express 2008 Visual Studio Express 2008
boost: tried both 1.44.0 and 1.46.1 提升:尝试1.44.0和1.46.1
Linking ( tried both dynamic and static ) 链接(尝试动态和静态)
The basic problem is that in the current standard there is no support for moving exceptions from one thread to another. 基本问题是,在当前标准中,不支持将异常从一个线程移动到另一个线程。 When the exception is left uncaught in the newly created thread, it reaches the top of the stack and finalizes the program as if an exception had been left uncaught in main
. 当异常在新创建的线程中保持未被捕获时,它将到达堆栈的顶部并完成程序,就好像在main
未被捕获的异常一样。 Consider that the try
in main
is in the stack of the main thread, but the exception is in a completely different stack. 考虑main
中的try
是在主线程的堆栈中,但异常是在完全不同的堆栈中。
That is documented in boost thread: http://www.boost.org/doc/libs/1_46_1/doc/html/thread/thread_management.html#thread.thread_management.thread 这在boost线程中有记录: http : //www.boost.org/doc/libs/1_46_1/doc/html/thread/thread_management.html#thread.thread_management.thread
In the upcoming standard there is support for moving exceptions from one thread to another, but you would have to either catch and move manually or use a higher level constructs like std::future
. 在即将推出的标准中,支持将异常从一个线程移动到另一个线程,但您必须手动捕获和移动或使用更高级别的构造,如std::future
。
You are throwing an exception in the thread and there is no surrounding catch block to catch the exception. 你在线程中抛出一个异常,没有周围的catch块来捕获异常。 The handler is around the place where you create the thread but the thread is running in it own separate context. 处理程序位于您创建线程的位置,但线程在其自己的单独上下文中运行。
If you want to catch an exception thrown in the thread then you need to do so inside that thread. 如果你想捕获线程中抛出的异常,那么你需要在该线程内执行此操作。
Boost.Exception has a way of transporting of exceptions between threads described in http://www.boost.org/doc/libs/release/libs/exception/doc/tutorial_exception_ptr.html Boost.Exception有一种在http://www.boost.org/doc/libs/release/libs/exception/doc/tutorial_exception_ptr.html中描述的线程之间传输异常的方法。
This is also part of the upcoming C++0X standard. 这也是即将推出的C ++ 0X标准的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.