2017-05-31 55 views
10

在哪个线程被称为终止处理程序:在哪个线程中调用了终止处理程序?

  1. 当一个例外是noexcept函数内抛出?

  2. 当用户拨打std::terminate()?

  3. 在启动或销毁thread

是否在标准中定义,我是否可以访问thread_local对象?在注释中给出

+1

我的常识告诉我,它会调用线程调用'std :: terminate'?我确实相信标准没有明确地解决这个问题。 – DeiDei

+0

我相信这是不明确的行为(或可能是undefined?) –

+0

我会说在实际设置处理程序的线程,虽然idk –

回答

2

这个答案总结答案,现在删除了一个答案:

  • 它不是标准中所规定(DeiDei,我已经在N4618检查过)

  • 然而,由于技术原因,该处理程序不太可能在其他线程中被调用,该线程导致呼叫std::terminateGalik,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