C++ 中分离线程的资源释放
Resource deallocation for Detach thread in C++
我正在经历 this post 堆栈溢出,其中接受的答案是:
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.
虽然在 post 中接受的答案是:
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;
}
那么,为什么在堆栈溢出的许多 post 中,即使主线程退出,分离线程也会在后台继续 运行ning?在什么情况下,分离线程在主程序退出时继续在后台 运行 以及以上哪一个陈述是正确的?
提前致谢。
标准将线程的范围定义为程序:
1.10/1: A thread of execution (also known as a thread) is a single flow of control within a program (...) The execution of the entire program consists of an execution of all of its threads.
标准关于分离线程的说法:
30.3.3/1: A thread of execution is detached when no thread object represents that thread.
所以标准中没有任何内容表明线程可以在其程序中存活下来。
如果你想在程序结束后在后台保留一些东西 运行ning,你必须分叉或创建一个单独的进程,该进程将 运行 在后台使用自己的资源和线程。
我正在经历 this post 堆栈溢出,其中接受的答案是:
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.
虽然在
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;
}
那么,为什么在堆栈溢出的许多 post 中,即使主线程退出,分离线程也会在后台继续 运行ning?在什么情况下,分离线程在主程序退出时继续在后台 运行 以及以上哪一个陈述是正确的?
提前致谢。
标准将线程的范围定义为程序:
1.10/1: A thread of execution (also known as a thread) is a single flow of control within a program (...) The execution of the entire program consists of an execution of all of its threads.
标准关于分离线程的说法:
30.3.3/1: A thread of execution is detached when no thread object represents that thread.
所以标准中没有任何内容表明线程可以在其程序中存活下来。
如果你想在程序结束后在后台保留一些东西 运行ning,你必须分叉或创建一个单独的进程,该进程将 运行 在后台使用自己的资源和线程。