当主进程终止时,该进程创建的所有工作线程也会被杀死。因此,如果在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
main
在返回之前等待分离的工作线程的解决方法是使用condition_variable
. 例如:
#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;
}