[英]Why does this simple threaded C++ program crash upon exit unless I call thread.join()?
The program below will end up failing with a message regarding abort()
being called. 下面的程序最终会失败,并显示有关调用
abort()
的消息。
I'm starting a thread that simple prints to cout
. 我正在开始一个简单的打印到
cout
的线程。 If I use std::this_thread::sleep_for()
, I get the error. 如果我使用
std::this_thread::sleep_for()
,我会收到错误。 If I remove this, I get the error. 如果我删除它,我收到错误。 If I call
join()
on the thread, everything works fine. 如果我在线程上调用
join()
,一切正常。
Shouldn't the thread have terminated long before the 1000 ms delay was up? 线程是否应该在1000毫秒延迟之前很久终止? Why is this causing an error?
为什么会导致错误? I can't believe calling
join()
is a requirement for a thread. 我不敢相信调用
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;
}
According to cppreference on thread class destructor : 根据线程类析构函数的cppreference :
~thread()
: Destroys the thread object.~thread()
:销毁线程对象。 If*this
still has an associated running thread (iejoinable() == true
),std::terminate()
is called.如果
*this
仍然有一个关联的运行线程(即joinable() == true
),则调用std::terminate()
。
And joinable()
: 和
joinable()
:
[...] A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.
[...]已完成执行代码但尚未加入的线程仍被视为活动执行线程,因此可以连接。
So you have to call join()
explicitely before your thread variable is automatically destroyed or use the detach()
member function. 因此,在自动销毁线程变量或使用
detach()
成员函数之前,必须明确地调用join()
。
Check cppreference's std::thread
page . 检查cppreference的
std::thread
页面 。
A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.
已完成执行代码但尚未加入的线程仍被视为活动执行线程,因此可以连接。
[
the destructor
] Destroys the thread object.[
the destructor
]销毁线程对象。 If*this
still has an associated running thread (iejoinable() == true
),std::terminate()
is called .如果
*this
仍然有一个关联的运行线程(即joinable() == true
), 则调用std::terminate()
。
To get the behavior you want, you'd need to call _t.detach()
before exiting from main
: 要获得所需的行为,您需要在退出
main
之前调用_t.detach()
:
[
detach()
] Separates the thread of execution from the thread object, allowing execution to continue independently.[
detach()
]将执行线程与线程对象分开,允许执行独立继续。 Any allocated resources will be freed once the thread exits.线程退出后,将释放任何已分配的资源。 After calling
detach
*this
no longer owns any thread.在调用
detach
*this
不再拥有任何线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.