Vinodini Natrajan
Vinodini Natrajan

Reputation: 155

Does detached thread leaks memory C++ after exit

I have an use case where I have to stop the thread from within itself. So I was thinking to detach it and once the call the stop method (which would complete the execution of the thread).

So does it leak memory after detach ? If so, how should this be handled ?

Upvotes: 2

Views: 2000

Answers (1)

Bitwize
Bitwize

Reputation: 11210

There is no way to "stop" a specific thread that is detached unless the thread actually exits (e.g. returns), so it depends on what you mean. At least, this is not possible with standard C++ threads.

If you are asking whether a thread that returns will automatically clean up resources, the answer is no -- it will not. Any RAII objects that clean up resources in their destructors will be called, but anything explicitly allocated will not be cleaned up and will require code to do this manually.

If you are thinking of something like pthread_cancel, then most likely it will not be cleaned up since this is a C API and cancellation does not insert a return that performs destructor cleanup. I strongly advise against doing this sort of thing.

If by "stop"ing from the thread you actually mean something like std::exit, then this is dependent on the underlying operating system you are using. Destructors will not be run, so any specific clean up code will not be performed; however on most modern OSes any used resources like open memory will be cleaned up on program termination. However, there are some systems out there that don't do this (usually specialized/embedded RTOS)


The best way to prevent any type of leak with a detached thread is to be able to signal to it when you want it to complete, and to always use RAII objects so that cleanup will be automatic.

With you can actually use std::stop_token for this, but in anything before that you can simply devise a synchronization system from a std::shared_ptr<std::atomic<bool>> and querying this within the thread as a "cancellation point".

Upvotes: 2

Related Questions