线程对象的生命周期、线程等待和分离 #include <iostream> #include<thread> using namespace std; bool is_exit = false;//用于判断主线程是否退出 void ThreadMain() { cout << "begin sub thread main ID: " << this_thread::get_id() << endl; //释放CPU for (int var = 0; var < 10; ++var) { if(!is_exit) break; cout <<"in thread"<<var<<endl; this_thread::sleep_for(1s); } cout << "end sub thread main ID:" << this_thread::get_id() << endl; } int main() { { //thread th(ThreadMain);//出错 } { thread th(ThreadMain); th.detach();//子线程与主线程分离,守护线程 //注意:主线程退出后,子线程不一定退出 } { thread th(ThreadMain); this_thread::sleep_for(1s); cout<<"主线程阻塞,等待子线程退出"<<endl; is_exit = true;//通知子线程退出 th.join();//主线程阻塞,等待子线程退出 cout<<"子线程已经退出"<<endl; } return 0; }