c++ - Exception not caught if raised after spawning std::thread -


i'm puzzled strange behavior of exceptions, thrown in main thread after spawning thread:

void thread_body(){     while(true) cout << "in thread" << endl; }  int main(int argc, char** argv) {     try{         auto t = std::thread( thread_body );          throw std::runtime_error("error!");          t.join();     } catch (const std::exception& e) {         cout << e.what() << endl;     } } 

the output is:

in thread in thread in thread terminate called without active exception program has unexpectedly finished. 

if throw before spawning thread this:

throw std::runtime_error("error!"); auto t = std::thread( thread_body ); 

than caught normally:

error!

why exception not caught in first case? should catch in usual way?

when exception thrown thread object destroyed. thread destructor called while still joinable. causes terminate called exception handler never invoked.

also writing standard streams different threads without proper synchronization not idea.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -