【问题标题】:Valgrind output when all the threads do not terminate所有线程未终止时的 Valgrind 输出
【发布时间】:2015-02-21 08:46:55
【问题描述】:

这更像是一个一般性的查询,如果产生的一些线程没有正常终止,valgrind memcheck 的行为会是什么。我的意思是线程分离并且不与父进程/线程共享任何内存的情况。

我没有任何代码 sn-p 或 valgrind 输出,因为这是一个出于好奇而提出的问题

【问题讨论】:

    标签: c linux memory memory-leaks valgrind


    【解决方案1】:

    对于这段代码:

    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() 创建的线程呢? ,它会获得一些自己的内存(当然是在进程中),并且在父线程关闭时不会被取消分配,因为它是一个分离的线程。
    • 主线程不等待他的孩子,所有打开的线程都被中断,因此你可能会出现内存泄漏,使用互斥锁来同步线程
    • '当父线程关闭时不会取消分配,因为它是一个分离的线程' - 确实如此。进程终止意味着进程中所有线程的死亡,然后释放所有堆栈等内存。每当任何进程线程调用进程终止时,操作系统可以并且将终止所有线程,处于任何状态,无论是否在任何内核上运行。不会有任何泄漏。
    猜你喜欢
    • 1970-01-01
    • 2015-06-24
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    相关资源
    最近更新 更多