In which thread is called the terminate handler:
when an exception is thrown inside a noexcept
function?
when the user call std::terminate
()?
at start up or destruction of thread
?
Is it defined in the standard, will I have access to thread_local
objects?
A thread automatically terminates when it returns from its entry-point routine. A thread can also explicitly terminate itself or terminate any other thread in the process, using a mechanism called cancelation.
The C++11 does not have direct method to terminate the threads. The std::future<void> can be used to the thread, and it should exit when value in future is available. If we want to send a signal to the thread, but does not send the actual value, we can pass void type object.
In C++11 std::terminate is called always when destructor throws. In fact, this change may be helpful. We will explain that in the next post. In general, any function annotated with noexcept calls std::terminate when it attempts to throw.
std::terminate is what is automatically called in a C++ program when there is an unhandled exception. This is essentially the C++ equivalent to abort , assuming that you are reporting all your exceptional errors by means of throwing exceptions.
This answer sum up answers given in comments and an answer now deleted:
It is not specified in the standard (DeiDei, I have checked too in N4618)
Nevertheless, for technical reasons it is unlikely that the handler is called in an other thread that the one who caused the call to std::terminate
(Galik,Hans Passant)
it has been verified on online compiler (Rinat Veliakhmedov), the terminate handler is called in the thread that causes terminate to be called.
You can test it yourself with this code from a deleted answer:
#include <string>
#include <exception>
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mutex;
const auto& id = std::this_thread::get_id;
const auto print = [](std::string t){
std::lock_guard<std::mutex> lock(mutex);
std::cout << id() << " " << t << std::endl;
};
void my_terminate_handler(){
print("terminate");
std::abort();
}
void throwNoThrow() noexcept { throw std::exception(); }
void terminator() { std::terminate(); }
int main() {
std::set_terminate(my_terminate_handler);
print("main");
#ifdef CASE1
auto x1 = std::thread(throwNoThrow);
#elif CASE2
auto x1 = std::thread(terminator);
#elif CASE3
auto x1 = std::thread(throwNoThrow);
#endif
x1.join();
}
Conclusion It is unspecified but it seems that the handler is always be called in the thread that causes std::terminate
to be called. (tested on gcc-5.4, gcc-7.1, clang-3.8 with pthreads)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With