我正在测试新的 C++11 线程功能。为此,我通过向其构造函数提供一个 lambda 表达式来启动一个线程:
int main()
{
thread t([]() {
cout << "Hello World!" << endl;
});
//this_thread::sleep_for(chrono::seconds(5));
cout << "I am done!" << endl;
getchar();
return 0;
}
但是在我按下一个键(getchar
)之后,我得到了错误:
谁能给个理由?
最佳答案
您看到的行为是预期的,下面解释了如何避免它。
来自std::thread::~thread documentation .
If *this has an associated thread (joinable() == true), std::terminate() is called.
A thread object does not have an associated thread (and is safe to destroy) after
- it was default-constructed
- it was moved from
- join() has been called
- detach() has been called
So what? I understand that join() must only be called for the main thread to wait for the worker thread. In this case, there is no purpose in waiting, because I press a key.
为什么等待没有意义?如果 main
函数在线程使用 std::cout
流对象之前完成执行会发生什么情况(尽管不太可能,即使您有 getchar ()
调用)?该全局流对象是否仍然对线程使用有效?
关于c++ - 为什么此 C++ 线程代码会触发 abort() 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35754215/