为什么这个简单的线程c++程序在退出时崩溃,除非我调用thread.join()
Why does this simple threaded C++ program crash upon exit unless I call thread.join()?
下面的程序最终将失败,并显示有关abort()
被调用的消息。
我开始一个线程,简单打印到cout
。如果我用std::this_thread::sleep_for()
,我得到错误。如果移除这个,就会出现错误。如果我在线程上调用join()
,一切工作正常。
线程不应该在1000毫秒延迟结束之前就终止吗?为什么这会导致错误?我不敢相信调用join()
是一个线程的要求。
#include <thread>
#include <iostream>
class ThreadTest
{
public:
ThreadTest() : _t{ &ThreadTest::Run, this } {}
void Wait() { _t.join(); }
private:
void Run(){
std::cout << "In thread" << std::endl;
}
std::thread _t;
};
int main(int argc, char *argv[])
{
ThreadTest tt;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// tt.Wait();
return 0;
}
根据线程类析构函数的cppreference:
~thread()
:销毁线程对象。如果*this
仍然有一个相关联的正在运行的线程(即joinable() == true
),则调用std::terminate()
。
And joinable()
:
[…一个线程如果已经完成了代码的执行,但是还没有被join,它仍然被认为是一个活动的正在执行的线程,因此是可join的。
所以你必须在你的线程变量被自动销毁或使用detach()
成员函数之前显式地调用join()
。
查看cppreference的std::thread
页面
如果一个线程已经完成了代码的执行,但是还没有被连接,那么它仍然被认为是一个正在执行的活动线程,因此是可连接的。
[
the destructor
]销毁线程对象。如果*this
还有一个相关联的运行线程(即joinable() == true
),则调用std::terminate()
。
要获得你想要的行为,你需要在退出main
之前调用_t.detach()
:
[
detach()
]将正在执行的线程从线程对象中分离出来,允许独立地继续执行。一旦线程退出,任何分配的资源都将被释放。调用detach
后,*this
不再拥有任何线程。
- 如何确定我已使用非编码文件到达 EOF?
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 为什么我的多线程作业队列崩溃
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 我在 C++ 代码中遇到错误警告:控制到达非空函数 [-Wreturn 类型] 的末尾
- 为什么当我尝试搜索双链表中第一个数据条目之外的数据时,程序崩溃了?
- 我想使用哈希图打印非重复的数字;
- 指针相关的UE4崩溃.我的指针哪里错了?
- 您好,我实际上想了解以下代码.有人可以详细说明代码它到底在做什么吗?为什么它会在第 31 行崩溃
- 拖放我的MDI被CRichEditView拦截并在CRichEditView::GetDocument中崩溃 - 如何覆
- 为什么定义复制构造函数会给我错误:无法将类型 'obj&' 的非常量左值引用绑定到类型为"obj"的右值?
- 为什么我的结构在包含字符串时崩溃?
- 无法访问的代码如何导致我的程序崩溃?
- 矢量迭代器在尝试调用函数时使我的程序崩溃
- 使用唯一指针调用函数会使我的程序崩溃
- 为什么我总是收到此错误:从类型为"农场动物"的右值初始化类型的非常量引用无效|
- 我想获取点的属性,它报告错误 C3867:"point::output_x":非标准语法;使用"&"创建指向成员的指针
- 钩/绕道 d3d9 (现在/结束场景) - 似乎调用我的函数然后崩溃
- C++单例模板类使我的程序崩溃