一.主线程结束,detch的线程即便是死循环,也依旧会被终止。ios
#include<iostream> #include<thread> using namespace std; void f() { int i = 0; while (true) { cout << "i=" << i << endl; i++; } } int main(int argc, int * argv[]) { thread t(f); t.detach(); cout << "main" << endl; //system("pause"); return 0; }
在mian结束后,t线程也会结束,进程都结束了,线程资源固然也得回收。spa
二.使用detch来实现守护线程,主线程不能结束。线程
#include<iostream> #include<thread> using namespace std; void f() { int i = 0; while (true) { cout << "i=" << i << endl; i++; } } int main(int argc, int * argv[]) { thread t(f); t.detach(); cout << "main" << endl; while (true) { } return 0; }
结果以下:code