gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:45:05 26 4
gpt4 key购买 nike

我正在浏览 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发布接受的答案说:

当 main() 退出时进程终止,所有线程都被杀死。

为了查看行为,我在 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;
}

那么,为什么这里的许多关于堆栈溢出的帖子都建议分离线程继续在后台运行,即使主线程退出也是如此?在什么情况下 detach 线程在 main 退出时继续在后台运行,以上说法中哪一个是正确的?

提前致谢。

最佳答案

标准将线程的范围定义为程序:

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.

所以标准中没有任何内容表明线程可以在其程序中存活下来。

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

关于c++ - C++ 中分离线程的资源释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40357447/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com