【发布时间】:2016-11-01 09:39:56
【问题描述】:
我正在查看 this 关于堆栈溢出的帖子,其中接受的答案是:
what happens to a detached thread when main() exits is:
It continues running (because the standard doesn't say it is stopped), and that's well-defined, as long as it touches neither (automatic|thread_local) variables of other threads nor static objects.
虽然在this 的帖子中接受的答案是这样的:
Process terminates when main() exits, and all threads are killed.
为了查看行为,我在 g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4 上测试了下面的代码,这表明一旦主线程退出,其他分离线程也会退出。
#include <iostream>
#include <thread>
#include <unistd.h>
#include <fstream>
using namespace std;
void foo()
{
std::cout<<"Inside foo\n";
int i=0;
ofstream myfile;
while(i<10)
{
std::cout<<"Inside while\n";
myfile.open ("/home/abc/example.txt",ios::app);
myfile << "Writing this to a file.\n";
myfile.close();
i++;
sleep(1);
}}
int main()
{
std::thread first (foo);
first.detach();
sleep(5);
return 0;
}
那么,为什么在许多关于堆栈溢出的帖子中,即使主线程退出,分离线程也会继续在后台运行?什么情况下分离线程在主退出时继续在后台运行,上面哪一个是正确的?
提前致谢。
【问题讨论】:
-
您应该阅读关于您的第一个链接的已接受答案的评论。当
main()退出时,分离的线程将不复存在。 -
当一个进程结束时,所有与该进程相关的线程都会被清理掉。
-
@πάνταῥεῖ 我的错。我错过了阅读有关该答案的评论。感谢您指出。
标签: c++ multithreading c++11 stdthread detach