I have some code that dynamically allocates a new std::thread
from the C++11 <thread>
header, like this:
std::thread *th = new thread( /* my args */);
Some time later, I call join:
th->join();
Since I dynamically allocated the thread, do I also need to call delete th;
to free the memory? If I do, do I still need to call join()
first?
join() cannot be called on that thread object any more, since it is no longer associated with a thread of execution. It is considered an error to destroy a C++ thread object while it is still "joinable".
It has no other effect on the std::thread object -- in particular the std::thread object is not destroyed and continues to exist until someone else destroys it.
You could call std::terminate() from any thread and the thread you're referring to will forcefully end. You could arrange for ~thread() to be executed on the object of the target thread, without a intervening join() nor detach() on that object.
To avoid memory leaks, you need to both: join
a running thread, and make sure it is destructed/deleted (let it go out of scope for stack-allocated std::threads
or explicitly call delete for std::thread*
).
See thread::~thread in cppreference:
A thread object does not have an associated thread (and is safe to destroy) after:
- it was default-constructed
- it was moved from
- join() has been called
- detach() has been called
A non-joined thread, therefore, cannot be safely destructed.
A join()
ed std::thread
will still occupy some memory. Therefore you need to make sure it is properly deallocated if it is on the heap.
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