valgrind memory leak errors when using pthread_create

后端 未结 5 1061
离开以前
离开以前 2020-11-30 06:58

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:

相关标签:
5条回答
  • 2020-11-30 07:05

    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.

    0 讨论(0)
  • 2020-11-30 07:06

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

    0 讨论(0)
  • 2020-11-30 07:17

    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.

    0 讨论(0)
  • 2020-11-30 07:19

    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

    0 讨论(0)
  • 2020-11-30 07:23

    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()
    0 讨论(0)
提交回复
热议问题