在哪个线程中调用了终止处理程序?
问题描述:
在哪个线程被称为终止处理程序:在哪个线程中调用了终止处理程序?
当一个例外是
noexcept
函数内抛出?当用户拨打
std::terminate
()?在启动或销毁
thread
?
是否在标准中定义,我是否可以访问thread_local
对象?在注释中给出
答
这个答案总结答案,现在删除了一个答案:
它不是标准中所规定(DeiDei,我已经在N4618检查过)
然而,由于技术原因,该处理程序不太可能在其他线程中被调用,该线程导致呼叫
std::terminate
(Galik,Hans Passant)已经验证的在线编译器(里纳特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,铿锵3.8与pthreads)
我的常识告诉我,它会调用线程调用'std :: terminate'?我确实相信标准没有明确地解决这个问题。 – DeiDei
我相信这是不明确的行为(或可能是undefined?) –
我会说在实际设置处理程序的线程,虽然idk –