Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a detached std::thread need to be deleted after it terminates?

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?

like image 600
Stuart Barth Avatar asked Feb 04 '16 03:02

Stuart Barth


People also ask

What happens to a detached thread when main () exits?

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.

What happens to a thread when it finishes C++?

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.

What is a detached 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.

How do you delete a thread in C++?

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.


2 Answers

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.

like image 159
songyuanyao Avatar answered Sep 18 '22 09:09

songyuanyao


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.

like image 25
Victor Dyachenko Avatar answered Sep 21 '22 09:09

Victor Dyachenko