简体   繁体   English

是std :: thread的共享指针是一种不好的做法?

[英]is a shared pointer to std::thread a bad practice?

Does it make sense to use std::shared_ptr < std::thread> ? 使用std :: shared_ptr <std :: thread>是否有意义? The logic is simple: if thread is not needed, delete it, if new is required - realocate it. 逻辑很简单:如果不需要线程,删除它,如果需要new,则重新定位它。 is there any way to compare this concept with pooled threads? 有没有办法将这个概念与汇集线程进行比较?

I do know the exact ammount of threads in my system(I develop Image processing algorithm, and I wanted to give each child of "algorithm" class an individual thread (maybe to make it private, then no shared_ptr is required), where this algorithm will be running, and idle this private thread if no image was provided. Is it a bad concept? 我确实知道我系统中线程的确切数量(我开发了图像处理算法,我想给每个“算法”类的子项一个单独的线程(也许是为了私有,然后不需要shared_ptr),这个算法将运行,如果没有提供图像,则将此私有线程空闲。这是一个坏概念吗?

You probably miss the fact fact std::thread destructor does not terminate the thread. 您可能会错过事实,即std::thread析构函数不会终止该线程。 As already mentioned in the comments, if detach or join was not called before, std::thread destructor calls std::terminate . 正如评论中已经提到的, 如果之前没有调用detachjoinstd::thread析构函数会调用std::terminate In other words, std::shared_ptr<std::thread> is pretty useless. 换句话说, std::shared_ptr<std::thread>是没用的。

A std::thread is a rather low-level object. std::thread是一个相当低级的对象。 You may like to have a look at: 你可能想看看:

This answer is in the question: 这个答案是在这个问题中:

give each child of "algorithm" class an individual thread (maybe to make it private, then no shared_ptr is required) 给“算法”类的每个子节点一个单独的线程(可能使其成为私有,然后不需要shared_ptr)

Only use std::shared_ptr<> where ownership is genuinely shared. 仅使用std::shared_ptr<> ,其中所有权是真正共享的。

There's usually no harm in idle threads hanging about but on many systems there is an overhead of even a ceiling on thread instances even if many are not running. 空闲线程通常没有什么害处,但在许多系统上,即使很多线程实例没有运行,也会在线程实例上产生上限。

If there's a risk of thread proliferation or too much creating and destroying of threads and swapping, introduce a thread-pool and still don't use shared_ptr<> because the pool with own the threads. 如果存在线程扩散或创建和销毁线程和交换过多的风险,请引入线程池并仍然不使用shared_ptr <>,因为池具有自己的线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM