c++中分离线程的资源释放
Resource deallocation for Detach thread in C++
我正在阅读这篇关于堆栈溢出的文章,其中公认的答案是:
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或创建一个单独的进程,它将在后台运行,拥有自己的资源和线程。
相关文章:
- C++ 返回异常,我应该释放资源吗?
- 如何释放 googletest ASSERT_THROW语句中的函数使用的资源?
- 在不释放所有动态分配的资源的情况下结束程序是否有风险
- Tensorflow C++关闭会话后不释放 GPU 资源
- 谁负责释放由 std::move 移动的资源?
- 构造函数中发生异常时如何释放 API 使用的资源
- unique_ptr资源设置为 nullptr 后如何释放
- 提升 MPI 在侦听列表时不释放资源?
- 如何安全地释放构造函数分配的资源
- 通过C接口分配和释放资源的正确习惯用法
- 正在从D3D挂钩释放资源
- 如何释放局部变量拥有的资源
- 我们是否应该释放为 std::locale 分配的资源
- 如何从shared_ptr资源管理器释放资源
- boost:scoped_ptr to boost::p tr_vector 而不释放资源
- 为什么在此复制分配 ctor 结束时没有释放获取的资源?
- 使用 C++/WinAPI 在对话窗口中释放资源的相应消息是什么?
- Qt UI生成器不会释放资源
- Curl_easy_cleanup不会释放资源
- c++中分离线程的资源释放