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.
According to this article
Once detached, the thread should live that way forever.
forever? If the function of the thread finish, Does its resource remain forever?
According to this article
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)
Thanks for reading.
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.
After calling detach
*this
no longer owns any thread.
So to answer your questions (if they aren't already):
forever?
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?
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.
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.
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