使用pthread_create时valgrind内存泄漏错误

lim*_*lim 20 c++ valgrind memory-leaks pthreads

我正在使用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)  
Run Code Online (Sandbox Code Playgroud)

每次我调用pthread_create,使用某个函数 - 我在函数的末尾调用函数pthread_exit.因此,在验证这不是问题之后,可能是什么问题?

Alo*_*ave 36

线程的资源不会在终止时立即释放,除非线程是在detach state设置为属性的情况 下创建的PTHREAD_CREATE_DETACHED,或者pthread_detach是为其调用的pthread_t.

未分离的线程将保持终止状态,直到其标识符传递给pthread_joinpthread_detach.

总结一下,你有三个选择:

  1. 创建具有分离属性集的线程(PTHREAD_CREATE_DETACHED属性)
  2. 创建后(通过调用pthread_detach)分离您的线程,或
  3. 加入已终止的线程以回收它们(通过调用pthread_join).

心连心.


seh*_*ehe 5

如果线程不应加入(或仅自行过期),您可以使线程处于分离状态以避免内存泄漏。

要显式创建可连接或分离的线程,请使用 pthread_create() 例程中的 attr 参数。典型的 4 步过程是:

  • 声明一个pthread_attr_t数据类型的pthread属性变量
  • 初始化属性变量 pthread_attr_init()
  • 设置属性分离状态 pthread_attr_setdetachstate()
  • 完成后,释放属性使用的库资源 pthread_attr_destroy()

  • 啊,抱歉:`当第一次调用 main() 的线程以外的线程从用于创建它的启动例程返回时,就会对 pthread_exit() 进行隐式调用。函数的返回值将作为线程的退出状态` 你可以省略它 (2认同)

小智 5

当不使用可连接线程时,退出线程需要调用pthread_detach(pthread_self()) 以释放其所有资源。

  • pthread_detach(pthread_self()) 对我有用(阻止 valgrind 报告内存泄漏)。这种方法也很方便,因为在动态创建线程时,跟踪所有启动的线程并执行 pthread_join() 相当困难。 (3认同)