Delete std :: thread after calling the connection?

I have code that dynamically extracts a new std::thread from a C ++ 11 <thread> header, for example:

 std::thread *th = new thread( /* my args */); 

After some time, I call join:

 th->join(); 

Since I dynamically allocated the thread, I also need to call delete th; to free up memory? If so, do I need to call join() ?

+6
source share
2 answers

To avoid memory leaks, you need to: join working thread and make sure that it is destroyed / deleted (let it go out of scope for the std::threads allocated in the stack or explicitly call delete for std::thread* ).

See thread :: ~ thread in cppreference:

A stream object does not have an associated stream (and is safe to destroy it) after:

  • it was built by default
  • he was moved from
  • join () was called
  • Disabled () was called

An unbound stream, therefore, cannot be safely destroyed.

A join() ed std::thread will still occupy some memory. Therefore, you need to make sure that it is properly freed if it is on the heap.

+13
source

Yes, you must call join before destroying the stream object. If the destructor for the std::thread object that is joinable (i.e., if joinable returns true) is called, it is called std::terminate . Therefore, you must call join before destroying the stream by calling delete (for threads on the heap) or destroying it in normal mode.

To prevent a memory leak, you must call delete, as with any other variable allocated by the heap.

See std::thread for more details.

+5
source

Source: https://habr.com/ru/post/986702/


All Articles