c++ - 为什么此 C++ 线程代码会触发 abort() 错误?

标签 c++ multithreading c++11

我正在测试新的 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)之后,我得到了错误:

Debug

谁能给个理由?

最佳答案

您看到的行为是预期的,下面解释了如何避免它。

来自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/

相关文章:

c++ - 将二进制数据写入 ostream 时减少代码

c++ - C++ 包装类的含义是什么?

c++ - 便携性是汽车的一个问题吗?

c# - 关闭在 Windows 服务中等待计时器的线程

c++ - 查找多重集中小于或等于 k ​​的元素数

c++ - 用另一个元组中的元素填充一个元组

c++ - 函数调用以返回ListView_SetItemText宏内的字符串

c++ - Win32 消息循环中的键盘输入

java - 如何将 WaitForMultipleObjects 移植到 Java?

c# - 如何等待 ThreadState.Abort?