valgrind memory leak errors when using pthread_create

岁酱吖の 提交于 2019-11-27 04:37:23

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:

  1. create your thread with detached attribute set(PTHREAD_CREATE_DETACHED attribute)
  2. Detach your thread after creation (by calling pthread_detach), or
  3. Join with the terminated threads to recycle them (by calling pthread_join).

Hth.

micha

when not working with joinable threads the exiting thread needs to call pthread_detach(pthread_self()) in order to release all its resources.

sehe

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:

  • Declare a pthread attribute variable of the pthread_attr_t data type
  • Initialize the attribute variable with pthread_attr_init()
  • Set the attribute detached status with pthread_attr_setdetachstate()
  • When done, free library resources used by the attribute with pthread_attr_destroy()

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!