I\'m writing a program using the pthread library. When I run my program with the command valgrind --leak-check=full
, I get the following errors description:
Please note that the default pthread_create behavior is "joinable" NOT DETACHED. Therefore some OS resources would still remain in the process after pthread finished, which would result in zombie pthread and leads to increased VIRTUAL/resident memory usage.
The four solution @sehe mentioned would fix this problem.
However if you thread is a long-standing one, this might not be really needed. for example, if the pthread lives through the whole life of the process.
when not working with joinable threads the exiting thread needs to call pthread_detach(pthread_self())
in order to release all its resources.
A thread's resources are not immediately released at termination, unless
the thread was created with the detach state
attribute set to
PTHREAD_CREATE_DETACHED
, or if pthread_detach
is called for
its pthread_t
.
An undetached thread will remain terminated state until its identifier is passed to pthread_join
or pthread_detach
.
To sum it up, you have three options:
pthread_detach
), orpthread_join
).Hth.
In addition to the correct answers given you by other users, I suggest you to read this:
Tracking down a memory leak in multithreaded C application
You can make the thread in detached state to avoid the memory leak if the thread should not be joined (or just expires on it's own).
To explicitly create a thread as joinable or detached, the attr argument in the pthread_create() routine is used. The typical 4 step process is:
pthread_attr_t
data type pthread_attr_init()
pthread_attr_setdetachstate()
pthread_attr_destroy()