1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #include <iostream> #include <thread> #include <chrono>
using namespace std; using namespace std::chrono;
struct A { A() { cout << "A::A()" << endl; } ~A() { cout << "A::~A() " << endl; } };
void child() { A a; cout << "child" << endl; this_thread::sleep_for(chrono::seconds(3)); }
void parent() { cout << "parent" << endl; thread t{child}; t.detach();
}
int main() { parent(); cout << "main" << endl;
return 0; }
|
线程detach以后,如果进程结束(比如main函数返回)则该detached线程的资源交给系统回收,与该线程的父线程是否返回无关(除非父线程是main函数)