终止处理程序在哪个线程中调用?

In which thread is the terminate handler called?

本文关键字:线程 调用 处理 程序 终止      更新时间:2023-10-16

其中线程称为终止处理程序:

  1. noexcept函数内引发异常时?

  2. 当用户调用std::terminate()?

  3. 启动或销毁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();
}

结论它未指定,但似乎始终在导致调用std::terminate的线程中调用处理程序。(在gcc-5.4、gcc-7.1、clang-3.8 上使用 pthreads 进行测试)