一.主線程結束,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