Does it make sense to use std::shared_ptr < std::thread> ? The logic is simple: if thread is not needed, delete it, if new is required - realocate it. 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?
std::shared_ptr is not thread safe. A shared pointer is a pair of two pointers, one to the object and one to a control block (holding the ref counter, links to weak pointers ...).
Use shared_ptr if you want to share ownership of a resource. Many shared_ptr can point to a single resource. shared_ptr maintains reference count for this propose. when all shared_ptr's pointing to resource goes out of scope the resource is destroyed.
In C++, a shared pointer is one of the smart pointers. The shared pointer maintains a reference count which is incremented when another shared pointer points to the same object. So, when the reference count is equal to zero (i.e., no pointer points to this object), the object is destroyed.
The smart pointer has an internal counter which is decreased each time that a std::shared_ptr , pointing to the same resource, goes out of scope – this technique is called reference counting. When the last shared pointer is destroyed, the counter goes to zero, and the memory is deallocated.
You probably miss the fact fact std::thread
destructor does not terminate the thread. As already mentioned in the comments, if detach
or join
was not called before, std::thread
destructor calls std::terminate
. In other words, std::shared_ptr<std::thread>
is pretty useless.
A std::thread
is a rather low-level object. 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)
Only use std::shared_ptr<>
where ownership is genuinely shared.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With