11

在哪个线程中称为终止处理程序:

  1. 当函数内部抛出异常时noexcept

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

  3. 在启动或销毁thread

它是否在标准中定义,我可以访问thread_local对象吗?

4

1 回答 1

3

这个答案总结了评论中给出的答案,现在删除了一个答案:

  • 标准中没有规定(DeiDei,我在N4618也查过)

  • 然而,由于技术原因,处理程序不太可能在引起调用的另一个线程中调用std::terminateGalikHans 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上测试)

于 2017-05-31T17:55:08.807 回答