分离后C ++ 11线程会自动销毁吗 [英] Does C++ 11 thread automatically destroy after detach

查看:155
本文介绍了分离后C ++ 11线程会自动销毁吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我认为C ++ 11线程在分离后会自动销毁.但问题是,我找不到任何证据可以证明这一假设.

Normally, I would assume that C++ 11 thread automatically destroy after detach. But the thing is, I can't find anything to prove this assumption.

根据本文

一旦分离,线程应该永远那样生活.

Once detached, the thread should live that way forever.

永远吗?如果线程的功能完成了,它的资源是否会永远保留?

forever? If the function of the thread finish, Does its resource remain forever?

根据本文

调用此函数后,线程对象变得不可连接并且可以安全地销毁.

After a call to this function, the thread object becomes non-joinable and can be destroyed safely.

它可以安全地销毁,但是会自动销毁吗?

It can be destroyed safely, but is it automatically?

如果它不是自动销毁的,如何销毁它(不是强制性的,而是在线程功能结束之后)

If it's not destroyed automatically, how to destroy it (not forcefully, but after the function of the thread end)

感谢阅读.

推荐答案

您应该查阅更好的参考.来自 std :: thread :: detach :

You should consult a better reference. From std::thread::detach:

将执行线程与线程对象分离,从而允许执行独立地继续.线程退出后,将释放所有分配的资源.

Separates the thread of execution from the thread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits.

在调用detach * this 后不再拥有任何线程.

After calling detach *this no longer owns any thread.

因此,回答您的问题(如果尚未回答):

So to answer your questions (if they aren't already):

永远吗?

不.如果线程结束(例如:如果计数到10),则完成,并且不再运行.

No. If the thread finishes (for example: if it counts to 10), it is done and it is not running anymore.

它的资源会永远保留吗?

Does its resource remain forever?

否,当线程结束时,线程中的每个资源都将被释放(如变量等).

No, when the thread finishes, every resource from the thread is freed (like variables and such).

它可以安全地销毁,但是会自动销毁吗?

It can be destroyed safely, but is it automatically?

你是什么意思?线程完成后,无论是否调用 detach ,它都会被自动销毁.唯一的区别是,这里它们是指线程 object ,因此是实际的 std :: thread 实例.

What do you mean? When the thread is done, it is destroyed (automatically), regardless of whether you call detach or not. The only difference is that here, they are referring to the thread object, so the actual std::thread instance.

因此,在销毁线程对象时,无论您是否拥有实际线程已完成,都必须调用 join detach .如果不这样做,则会调用 std :: terminate .

So when the thread object is destructed, you must have called join or detach regardless whether you own that the actual thread finished or not. If you don't, std::terminate is called.

这篇关于分离后C ++ 11线程会自动销毁吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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