It would sometimes be useful if the connecting std::thread had hability to execute thread::join() in its destructor. See Examples below.
Example 1 (error): The std::thread object was destroyed after throwing an exception. When the thread goes out of scope, the destructor is called BEFORE JOINING. This makes the STL error message "abort".
int main( int argc, const char * argv[] ) { try { thread t( [] () { this_thread::sleep_for( chrono::seconds( 1 ) ); cout << "thread done" << endl; } ); throw exception( "some exception" ); t.join(); } catch ( const exception & ) { cout << "exception caught!" << endl; } cout << "main done" << endl; return 0; }
Example 2 (the correct path): An object t is created before my try-catch block, and join () is placed on both try and catch blocks. Thus, this ensures that the connection () occurs.
int main( int argc, const char * argv[] ) { thread t; try { t = thread( [] () { this_thread::sleep_for( chrono::seconds( 1 ) ); cout << "thread done" << endl; } ); throw exception( "some exception" ); t.join( ); } catch ( const exception & ) { t.join(); cout << "exception caught!" << endl; } cout << "main done" << endl; return 0; }
... AND QUESTION: What is the reason for a compatible std::thread not automatically joining its destructor?
It would be much easier if this happened automatically. As this is done today, you need to be careful if you use streams inside try-catch blocks, for example ... but I'm sure someone THOUGHT when designing std::thread this way. Therefore, there must be a reason for this ... what is the reason?
PS: I know that we can envolve std::thread in the class and put join() in the destructor of this new class ... so it becomes automatic. But it's not that. My question is really about std::thread .
c ++ multithreading language-lawyer thread-safety c ++ 11
Wagner patriota
source share