What is the reason for joining std :: thread to not join automatically?

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 .

+8
c ++ multithreading language-lawyer thread-safety c ++ 11
source share
1 answer

The reason is simply that you are forced to think about it. If the std::thread object is destroyed due to an exception that goes out of scope, then the connection can cause it to wait for a lock while unwinding the stack, which is often undesirable, and can lead to a deadlock if the thread that is waiting, in turn, waits some action from the side of the thread that is waiting.

Having completed the application in this situation, you, as a programmer, are forced to actively think about the conditions that could lead to the destruction of the object and ensure the correct connection of the stream.

+15
source share

All Articles