C++ cpp简单线程程序在退出时崩溃

C++ cpp简单线程程序在退出时崩溃,c++,multithreading,C++,Multithreading,我试图理解如何使用线程,而这段简单的代码因以下错误而崩溃: 守则: #include <iostream> #include <thread> #include <chrono> using namespace std; void thread1() { while (true) { cout << this_thread::get_id() << endl; } } void main(

我试图理解如何使用线程,而这段简单的代码因以下错误而崩溃:

守则:

#include <iostream>
#include <thread>
#include <chrono>

using namespace std;

void thread1()
{
    while (true)
    {
        cout << this_thread::get_id() << endl;
    }
}

void main()
{
    thread t1(thread1);
    thread t2(thread1);

    this_thread::sleep_for(chrono::seconds(1));

    t1.detach();
    t2.detach();
}

能解释一下为什么在分离后崩溃,如何修复这个问题?

< P>你为什么会出错,是因为在初始化后,访问CRT C++运行库。

工作线程通过访问std::cout使用CRT。当主线程离开主函数时,CRT库正在卸载,但工作线程仍在尝试使用它。可能会有一个运行时检查,所以您会得到一条错误消息,而不仅仅是程序崩溃


最好不要使用detach方法,并确保生成的所有线程都在程序退出时完成执行。

std::thread::detach通常是个坏主意。但我没有选择。通常,当程序退出时,操作系统应该回收所有非共享资源。但是在这种情况下,仍然有一些正在运行的线程,这使操作系统变得疯狂。我想最终编写一个多线程服务器,因此我必须学习如何使用这些命令。如何关闭它们?