Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete std::thread after calling join?

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?

like image 665
bobroxsox Avatar asked May 07 '15 01:05

bobroxsox


People also ask

Does join destroy a thread C++?

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".

Does std :: thread join on destruction?

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.

How do you end a thread in C++?

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.


1 Answers

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.

like image 60
EyasSH Avatar answered Sep 21 '22 11:09

EyasSH