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
Visual Studio Express 2008
boost: tried both 1.44.0 and 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. Consider that thetryinmainis in the stack of the main thread, but the exception is in a completely different stack.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
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.