Hes*_*Mad 3 c multithreading valgrind
我正在用C编写一个程序,该程序在threads完成时将永远不知道,所以我正在使用该程序pthread_detach()来释放内存,对吗?
这是代码:
pthread_t thread_id_Gruder, thread_id_Tavish;
estado_threadGruder = pthread_create(&thread_id_Gruder,NULL,SERVER_McGruderDedicado,&td_Gruder);
estado_threadTavish = pthread_create(&thread_id_Tavish,NULL,SERVER_McTavishDedicado,&td_Tavish);
if (estado_threadGruder != 0 || estado_threadTavish != 0) {
if (estado_threadGruder != 0) MSSG_error(THREAD_ERROR, "McGruder");
else MSSG_error(THREAD_ERROR, "McTavish");
raise(SIGINT);
pause();
}
pthread_detach(thread_id_Gruder);
pthread_detach(thread_id_Tavish);
Run Code Online (Sandbox Code Playgroud)
但是当我valgrind用来检查内存泄漏时,我发现了以下输出:
HEAP SUMMARY:
==19426== in use at exit: 544 bytes in 2 blocks
==19426== total heap usage: 15 allocs, 13 frees, 628 bytes allocated
==19426==
==19426== Thread 1:
==19426== 272 bytes in 1 blocks are possibly lost in loss record 1 of 2
==19426== at 0x4C31B25: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==19426== by 0x40134A6: allocate_dtv (dl-tls.c:286)
==19426== by 0x40134A6: _dl_allocate_tls (dl-tls.c:530)
==19426== by 0x4E44227: allocate_stack (allocatestack.c:627)
==19426== by 0x4E44227: pthread_create@@GLIBC_2.2.5 (pthread_create.c:644)
==19426== by 0x1097AA: main (in /users/home/alumnes/LS//PRACTICA/Lionel-S/Lionel)
==19426==
==19426== 272 bytes in 1 blocks are possibly lost in loss record 2 of 2
==19426== at 0x4C31B25: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==19426== by 0x40134A6: allocate_dtv (dl-tls.c:286)
==19426== by 0x40134A6: _dl_allocate_tls (dl-tls.c:530)
==19426== by 0x4E44227: allocate_stack (allocatestack.c:627)
==19426== by 0x4E44227: pthread_create@@GLIBC_2.2.5 (pthread_create.c:644)
==19426== by 0x1097CC: main (in /users/home/alumnes/LS//PRACTICA/Lionel-S/Lionel)
==19426==
==19426== LEAK SUMMARY:
==19426== definitely lost: 0 bytes in 0 blocks
==19426== indirectly lost: 0 bytes in 0 blocks
==19426== possibly lost: 544 bytes in 2 blocks
==19426== still reachable: 0 bytes in 0 blocks
==19426== suppressed: 0 bytes in 0 blocks
==19426==
==19426== For counts of detected and suppressed errors, rerun with: -v
==19426== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 0 from 0)
Run Code Online (Sandbox Code Playgroud)
我试图在没有该phtread_detach()函数的情况下运行代码,但valgrind显示出相同的内存泄漏,因此我假设我无法正确分离...
我是否正确分离了线程,或者问题出在线程内部?
谢谢。
问题很可能是您的线程。即使您没有malloc在其中使用任何东西。
这就是发生的情况,当您使用pthread_create创建线程时,该库会为线程的正确操作分配一堆东西,并开始运行它。通常,只有在使用来连接这些线程时,才释放这些东西pthread_join。但是,在某些情况下,您的代码中没有要同步线程的地方,只希望它们完成后消失。这就是为什么pthread_detach。分离的线程将在其运行时自动清除returns。注意,当他们返回时。
如果在程序完成时线程尚未完成,则主函数将正常运行,但线程仍在运行。由于尚未归还,因此仍未清除。
如果您打算让这些线程在程序完成之前运行,或者想在程序结束时等待它们没有完成,那么您确实想同步它们(在程序末尾),而pthread_detach可能不是要走的路。
如果您的线程有无限循环,建议您创建一个should_Terminate以0开头的变量,如果其值为1,则使线程中的循环中断。然后,当您要终止程序时将其设置为1,并用于pthread_join等待线程可以优雅地完成其工作。
如果它们没有无限循环,并且肯定会在某个时候返回,那么只需在程序末尾将它们加入即可。
| 归档时间: |
|
| 查看次数: |
218 次 |
| 最近记录: |