c++中分离线程的资源释放

Resource deallocation for Detach thread in C++

本文关键字:资源 释放 线程 分离 c++      更新时间:2023-10-16

我正在阅读这篇关于堆栈溢出的文章,其中公认的答案是:

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 foon";
int i=0;
ofstream myfile;

while(i<10)
{
    std::cout<<"Inside whilen";
    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;
}

那么为什么在这里的许多帖子堆栈溢出建议分离线程继续在后台运行,即使主线程退出?当主线程退出时,分离线程在什么条件下继续在后台运行,上面哪个语句是正确的?

标准将线程的作用域定义为程序:

1.10/1:一个执行线程(也称为线程)是在程序内的单个控制流(…)整个程序的执行包括所有线程的执行。

标准中关于分离线程的规定:

30.3.3/1:当没有线程对象代表一个正在执行的线程时,该线程被分离。

因此,标准中没有任何内容表明线程可以在其程序中存活。

如果你想在程序结束后保持后台运行,你必须fork或创建一个单独的进程,它将在后台运行,拥有自己的资源和线程。