Oli*_*liv 11 c++ terminate terminate-handler
在哪个线程中称为终止处理程序:
当noexcept函数内部抛出异常时?
当用户调用std::terminate()?
在启动或破坏thread?
它是否在标准中定义,我是否可以访问thread_local对象?
该答案总结了评论中给出的答案以及现已删除的答案:
标准中没有指定(DeiDei,我也在 N4618 中检查过)
然而,由于技术原因,处理程序不太可能在导致调用的线程std::terminate(Galik、Hans Passant)的另一个线程中调用
它已经在在线编译器(Rinat Veliakhmedov)上验证,终止处理程序在导致调用终止的线程中被调用。
您可以使用已删除答案中的以下代码自行测试:
#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();
}
Run Code Online (Sandbox Code Playgroud)
结论未指定,但似乎处理程序总是在导致std::terminate被调用的线程中被调用。(在gcc-5.4、gcc-7.1、clang-3.8 和 pthreads上测试)