分离后C ++ 11线程会自动销毁吗

编程入门 行业动态 更新时间:2024-10-28 19:28:17
本文介绍了分离后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线程会自动销毁吗

本文发布于:2023-10-13 14:15:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1488179.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!