C 所有螺纹未终止时的Valgrind输出
这更像是一个普通的查询,如果生成的一些线程没有正常终止,valgrind memcheck的行为会是什么。我指的是线程被分离并且不与父进程/线程共享任何内存的情况C 所有螺纹未终止时的Valgrind输出,c,linux,memory,memory-leaks,valgrind,C,Linux,Memory,Memory Leaks,Valgrind,这更像是一个普通的查询,如果生成的一些线程没有正常终止,valgrind memcheck的行为会是什么。我指的是线程被分离并且不与父进程/线程共享任何内存的情况 我没有任何代码片段或valgrind输出,因为这是一个出于好奇的问题对于这段代码: while (1) { pthread_t thread; struct sockaddr_in client; socklen_t len = sizeof(client); int newsock = accept(
我没有任何代码片段或valgrind输出,因为这是一个出于好奇的问题对于这段代码:
while (1) {
pthread_t thread;
struct sockaddr_in client;
socklen_t len = sizeof(client);
int newsock = accept(sock, (struct sockaddr *)&client, &len);
if (newsock == -1) {
perror("accept");
} else {
if (pthread_create(&thread, NULL, handle, &newsock) != 0) {
perror("pthread_create");
} else {
pthread_detach(thread);
}
}
if (count == 5) break;
}
close(sock);
exit(EXIT_SUCCESS);
如果线程仍在等待accept()
,它将显示可能丢失的:
david@debian:~$ valgrind ./server
==24561== Memcheck, a memory error detector
==24561== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==24561== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==24561== Command: ./server
==24561==
0
1
2
3
4
5
==24561==
==24561== HEAP SUMMARY:
==24561== in use at exit: 272 bytes in 1 blocks
==24561== total heap usage: 3 allocs, 2 frees, 1,408 bytes allocated
==24561==
==24561== LEAK SUMMARY:
==24561== definitely lost: 0 bytes in 0 blocks
==24561== indirectly lost: 0 bytes in 0 blocks
==24561== possibly lost: 272 bytes in 1 blocks
==24561== still reachable: 0 bytes in 0 blocks
==24561== suppressed: 0 bytes in 0 blocks
==24561== Rerun with --leak-check=full to see details of leaked memory
==24561==
==24561== For counts of detected and suppressed errors, rerun with: -v
==24561== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
如果进程在终止时没有失败,不用担心。在这种情况下,pthread_create()创建的线程会怎么样,它将获得自己的一些内存(当然,在进程中),并且在父线程关闭时不会取消分配,因为它是一个分离的线程。主线程不等待其子线程,并且所有打开的线程都被中断,因此您给出了一个可能的内存泄漏,使用互斥锁同步线程“在父线程关闭时不会取消分配,因为它是分离的线程”-确实如此。进程终止意味着进程中所有线程的死亡,以及随后所有堆栈等内存的释放。当任何进程线程调用进程终止时,操作系统可以并且将终止所有处于任何状态的线程,无论是否在任何内核上运行。不会有任何泄漏。