I create a new
std::thread object, and then detach()
it. The thread runs for an arbitrary amount of time, and then terminates itself. Since I created the object with new
, do I need to delete
it at some point to free up its resources? Or does the thread effectively delete
itself upon termination?
If it does effectively delete
itself, will something bad happen if I explicitly delete
it after it has terminated?
The answer to the original question "what happens to a detached thread when main() exits" is: It continues running (because the standard doesn't say it is stopped), and that's well-defined, as long as it touches neither (automatic|thread_local) variables of other threads nor static objects.
When you get to the end of your thread function, the thread ends. If the main thread exits while other threads are still running, bad things happen: it causes your program to crash. Always make sure your other threads exit before exiting the main thread.
Detach thread. Detaches the thread represented by the object from the calling thread, allowing them to execute independently from each other. Both threads continue without blocking nor synchronizing in any way. Note that when either one ends execution, its resources are released.
If the destructor for a std::thread object that is joinable (i.e. if joinable returns true) is called, it will call std::terminate . Therefore, you have to call join before destroying the thread, whether by calling delete (for threads on the heap) or by it being destroyed normally.
Yes, you have to delete
it by yourself.
Once you called std::thread::detach, the thread will be separated from the thread object and allowed execution to continue independently, and then the thread object will no longer owns any thread. So the thread won't and impossible to delete
it upon termination.
Every object in C++ allocated using new
must be released using delete
.
Thread is an object "located within OS" (usually). It is created using std::thread
constructor and released with detach()
.
Object of class std::thread
is a С++-object, associated with the thread.
So you have to release both - OS-object and C++-object.
Upd. When you create thread, OS allocates internal structures within kernel space to control it. There are set of properties associated with each thread like state (running, pending, waiting resource), priority, return code, etc.
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