【问题标题】:std::thread causes program to abortstd::thread 导致程序中止
【发布时间】:2020-06-20 18:06:56
【问题描述】:

我有以下代码sn-p:

#include <thread>
int main(){
    std::thread trial([](){ return 2;});
    //trial.join()
    return 0;
}

由此我得到以下输出:

terminate called without an active exception
[1]    17963 abort (core dumped)  ./a.out

现在,当我在创建线程后调用.join() 时不会发生这种情况。据我所知,.join() 一直等到线程执行结束。但是,它似乎也可以防止中止的发生。有人可以解释发生了什么吗?

【问题讨论】:

    标签: c++ multithreading c++11 abort


    【解决方案1】:

    有人能解释一下发生了什么吗?

    来自std::thread的析构函数的文档:

    如果 *this 有关联线程(joinable() == true),则调用 std::terminate()

    在例子中,你没有加入线程,所以当它被销毁时它是可加入的,因此进程std::terminate()被调用。默认情况下std::terminate() 调用std::abort

    如果你加入,那么在加入之后,线程将无法加入。因此std::terminate()不会在销毁时被调用。

    【讨论】:

    • 在 C++20 中有 std::jthread 在销毁时加入而不是终止程序
    猜你喜欢
    • 2015-11-21
    • 2023-03-31
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 2021-04-02
    • 2021-11-28
    • 1970-01-01
    相关资源
    最近更新 更多