说明:
- detach():分离,主线程不与子线程汇合,各自独立自行,主线程结束,子线程也能够运行;
- 一旦detach()后,与这个线程关联的thread对象就会失去与这个主线程的关联,此时子线程就会驻留后台运行;
- 这个子线程将会被系统运行时库接管,当这个子线程执行完成后,由运行时库负责清理该线程相关的资源(守护线程)
- 使用detach将会失去对线程的控制,join与detech不能同时使用
#include <thread>
#include <iostream>
using namespace std;
void thread_fun()
{
cout << "sub thread begin,thread ID: " << this_thread::get_id() << endl;
for (int i = 0; i < 10; i++) {
cout << "i= " << i << endl;
this_thread::sleep_for(chrono::seconds(1));
}
cout << "sub thread is over,thread ID: " << this_thread::get_id() << endl;
}
int main(int argc, char *argv[])
{
cout << "main thread begin,thread ID: " << this_thread::get_id() << endl;
thread th(thread_fun);
th.detach();
cout << "main thread is over,thread ID: " << this_thread::get_id() << endl;
return 0;
}