当主进程终止时,该进程创建的所有工作线程也将被终止。因此,如果main()
在它创建的一个分离线程完成执行之前返回,则该分离线程将被操作系统杀死。看下面这个例子:
void work(){
this_thread::sleep_for(chrono::seconds(2));
cout<<"Worker Thread Completed"<<endl;
}
int main(){
thread t(work);
t.detach();
cout<<"Main Returning..."<<endl;
return 0;
}
在上面的程序中,
Worker Thread Completed
永远不会被打印出来。因为
main
在工作线程的2秒延迟之前就返回了。现在,如果我们稍微改变一下代码,在
main
返回之前添加一个大于2秒的延迟。例如:
void work(){
this_thread::sleep_for(chrono::seconds(2));
cout<<"Worker Thread Completed"<<endl;
}
int main(){
thread t(work);
t.detach();
cout<<"Main Returning..."<<endl;
this_thread::sleep_for(chrono::seconds(4));
return 0;
}
输出
Main Returning...
Worker Thread Completed
现在,如果从除了
main
函数以外的任何函数中创建线程,则已分离的线程将保持活动状态,直到其执行完成,甚至在函数返回后仍然是如此。例如:
void child()
{
this_thread::sleep_for(chrono::seconds(2));
cout << "Worker Thread Completed" << endl;
}
void parent(){
thread t(child);
t.detach();
cout<<"Parent Returning...\n";
return;
}
int main()
{
parent();
cout<<"Main Waiting..."<<endl;
this_thread::sleep_for(chrono::seconds(5));
}
输出
Parent Returning...
Main Waiting...
Worker Thread Completed
使用
condition_variable
的一个解决方法,使得
main
在返回之前等待一个分离的工作线程。例如:
#include <bits/stdc++.h>
using namespace std;
condition_variable cv;
mutex m;
void work(){
this_thread::sleep_for(chrono::seconds(2));
cout << "Worker Thread Completed" << endl;
cv.notify_all();
}
int main(){
thread t(work);
t.detach();
cout << "Main Returning..." << endl;
unique_lock<mutex>ul(m);
cv.wait(ul);
return 0;
}
std::exit
或从main
退出之前终止每个线程是足够的,但不是必需的,以满足这些要求。"(可能整段都相关)。另请参阅[support.start.term]/8(当main
返回时调用std::exit
) - dyp