我正在使用pthread库编写程序。当我用命令valgrind --leak-check = full运行我的程序时,我得到以下错误描述:
==11784==
==11784== **HEAP SUMMARY:**
==11784== in use at exit: 4,952 bytes in 18 blocks
==11784== total heap usage: 1,059 allocs, 1,041 frees, 51,864 bytes allocated
==11784==
==11784== **288 bytes** in 1 blocks are possibly lost in loss record 2 of 3
==11784== at 0x4C2380C: calloc (vg_replace_malloc.c:467)
==11784== by 0x4010D2E: _dl_allocate_tls (dl-tls.c:300)
==11784== by 0x55DC218: **pthread_create**@@GLIBC_2.2.5 (allocatestack.c:570)
==11784== by 0x401BC0: initdevice(char*) (in /a/fr-01/vol/home/stud/lim/workspace /Ex3/l)
==11784== by 0x406D05: main (in /a/fr-01/vol/home/stud/lim/workspace/Ex3/l)
==11784==
==11784== **4,608 bytes** in 16 blocks are possibly lost in loss record 3 of 3
==11784== at 0x4C2380C: calloc (vg_replace_malloc.c:467)
==11784== by 0x4010D2E: _dl_allocate_tls (dl-tls.c:300)
==11784== by 0x55DC218: **pthread_create**@@GLIBC_2.2.5 (allocatestack.c:570)
==11784== by 0x40268F: write2device(char*, int) (in /a/fr-01/vol/home/stud/lim/workspace/Ex3/l)
==11784== by 0x406D7B: main (in /a/fr-01/vol/home/stud/lim/workspace/Ex3/l)
==11784==
==11784== **LEAK SUMMARY:**
==11784== definitely lost: 0 bytes in 0 blocks
==11784== indirectly lost: 0 bytes in 0 blocks
==11784== possibly lost: 4,896 bytes in 17 blocks
==11784== still reachable: 56 bytes in 1 blocks
==11784== suppressed: 0 bytes in 0 blocks
==11784== Reachable blocks (those to which a pointer was found) are not shown.
==11784== To see them, rerun with: --leak-check=full --show-reachable=yes
==11784==
==11784== For counts of detected and suppressed errors, rerun with: -v
==11784== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 4 from 4)
每当我调用pthread_create时,使用某个函数 - 我在函数的末尾调用函数pthread_exit。因此,在验证这不是问题后,可能是什么问题?
答案 0 :(得分:33)
线程的资源不会在终止时立即释放,除非
该线程是在detach state
属性设置为的情况下创建的
PTHREAD_CREATE_DETACHED
,或者如果要求pthread_detach
它的pthread_t
。
未分离的线程将保持终止状态,直到其标识符传递给pthread_join
或pthread_detach
。
总结一下,你有三个选择:
pthread_detach
)或pthread_join
)。H个。
答案 1 :(得分:4)
当不使用可连接线程时,退出线程需要调用pthread_detach(pthread_self())
为了释放所有资源。
答案 2 :(得分:3)
你可以让线程in detached state避免内存泄漏,如果线程不应该加入(或者只是自己过期)
要将线程显式创建为可连接或已分离,请使用pthread_create()例程中的attr参数。典型的4步过程是:
答案 3 :(得分:0)
除了其他用户给出的正确答案外,我建议您阅读:
答案 4 :(得分:0)
请注意,默认的pthread_create行为是"可加入"没有拆除。 因此,在pthread完成后,某些OS资源仍将保留在进程中,这将导致僵尸pthread并导致VIRTUAL /驻留内存使用量增加。
提到的四个解决方案@sehe将解决这个问题。
但是如果你的线程很长,那可能就不需要了。 例如,如果pthread贯穿整个过程的生命。