NoSenseEtAl
NoSenseEtAl

Reputation: 30138

Why do unjoined pthreads leak resources when thread is not detached after pthread_create

I took an example from

https://www.kernel.org/doc/man-pages/online/pages/man3/pthread_create.3.html

made it run infinitely(with small sleep so CPU usage isnt a bottleneck so no queuing up of threads) by creating threads with pthread_create without ever calling pthread_join. That causes memory leaks and eventually PC runs out of memory. When I added pthread_detach immediately after creating the thread program behaves nicely and memory usage is constant after some time.

I was under impression that when a thread exits ( at closing } of the function that if given to pthread_create) all its resources are cleaned.

Upvotes: 3

Views: 724

Answers (1)

nos
nos

Reputation: 229334

I was under impression that when a thread exits ( at closing } of the function that if given to pthread_create) all its resources are cleaned.

That's a wrong impression. As you say, all resources are released for a finished thread when you either call pthread_join, or the thread is a detached thread.

For a non-detached thread, some resources have to be kept around - otherwise you couldn't get at the return value of the thread with a later call to pthread_join. A detached thread cannot be joined, so you can't get an exit value from it.

Many implementations store this return value on the stack of the thread, and thus keeps the entire stack around until someone calls pthread_join on a non-detached thread.

Upvotes: 10

Related Questions