【发布时间】:2017-06-29 23:19:13
【问题描述】:
我正在尝试了解如何使用线程,而这个简单的代码会因以下错误而崩溃:
代码:
#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();
}
谁能解释一下为什么它在分离后崩溃以及如何解决这个问题?
【问题讨论】:
-
std::thread::detach()通常是个坏主意。 -
但我别无选择
-
非正式地,当您的程序退出时,操作系统应回收所有(非共享)资源。但是在这种情况下,仍然有一些正在运行的线程,这让操作系统很生气。
-
我想最终写一个多线程服务器,所以我必须学习如何使用这些命令
-
那么我该如何关闭它们呢?
标签: c++ multithreading