漏洞std :: thread未定义的行为? [英] Is leaking std::thread undefined behaviour?

查看:160
本文介绍了漏洞std :: thread未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人会感兴趣的原因

  // ... 
new std :: thread ,arg1,arg2);

}

std :: thread destructor(不像 boost :: thread )杀死线程。 func完成是一些时间。
我的问题是这种情况下的安全:



情况1:让我们说函数以值为arg1,arg2。

情况2 :让我们说arg1,arg2通过引用 - 这听起来不错,如果你问我,因为我假设在作用域的末端arg1和arg2将被它们的析构函数清除。



BTW是std :: thread destructor(当func结束时调用AFAIK)聪明到足以清除线程使用的所有资源?我的意思是如果我创建1M线程(ofc不在同一时间)与新的和所有的完成,我有永久泄漏的东西?

解决方案

std :: thread对象表示一个线程,它不是一个真正的线程,操作系统。



因此,在这里你泄漏一个std :: thread对象,因为你不删除它。



如果析构函数在指令结束前调用,例如,如果您创建了对象在堆栈和有很多事情要做在这个新的线程,然后析构函数调用将触发std :: terminate()。 您需要调用detach(),以允许线程在std :: thread实例销毁后继续。



方式,你必须明确地说,如果你想要或不是这个线程结束时std ::线程实例被销毁:如果你想要继续,调用detach();如果你想等待它结束,调用join()。



所以在你的情况下,内存泄漏,但线程应继续std ::线程对象永远永远,因为你失去了控制它的任何方式。


Reason why somebody would be interested in

  //...
 new std::thread (func,arg1,arg2);

}

is that std::thread destructor(unlike boost::thread) kills the thread. func finishes is some time. My question is this safe in cases:

Case 1: lets say that function takes arg1, arg2 by value.
Case 2: lets say that function takes arg1, arg2 by reference-this sounds bad if you ask me, because I presume that at the end of the scope where thread is created arg1 and arg2 will be cleared by their destructors.

BTW is std::thread destructor(that is AFAIK called when func finishes) smart enough to clear all the resources used by thread? I mean if I create 1M threads(ofc not at the same time) with new and all of them finish, have I leaked anything permanently?

解决方案

An std::thread object represents a thread, it is not a "real" thread, that is a concept managed by the OS.

Therefore, here you're leaking a std::thread object because you don't delete it. The destructor is never called. But the thread it was representing will end when it's instructions will end, like any thread.

If the destructor was called before the end of the instructions, for example if you would have created that object on the stack and there was a lot of things to do in this new thread, then the destructor call would have triggered std::terminate(). You need to call detach() to allow the thread to continue after the std::thread instance is destroyed.

That way, you have to explicitely say if you want or not this thread to end when the std::thread instance is destroyed : if you want it to continue, call detach(); if you want to wait for it to end, call join().

So in your case you leak memory but the thread should continue as the std::thread object lives "forever" because you lost any way to control it.

这篇关于漏洞std :: thread未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆