【问题标题】:Pthreads leak memory even if used correctly即使正确使用 Pthreads 也会泄漏内存
【发布时间】:2015-03-04 10:11:25
【问题描述】:

我已经为此奋斗了很长时间。环顾四周,我似乎无法找到答案。我只是创建了两个分离的线程,然后在它们上都使用pthread_exit(),但时不时会出现泄漏。

因为我知道人们会问我:

  1. 是的,我已阅读所有其他问题,但没有真正的答案
  2. 我将线程标记为detached
  3. 我给enough time 让线程初始化并终止
  4. 我已经阅读了 pthread_exit 的手册,并且使用正确
  5. 与-Wall 编译良好​​strong>

代码:

int threads_keepalive = 1;

void* thread_do(void *arg){
    while(threads_keepalive)
        sleep(1);
    pthread_exit(NULL);
}

int main(){

    /* Make threads */
    pthread_t* threads;
    threads = malloc(2 * sizeof(pthread_t));
    pthread_create(&threads[0], NULL, thread_do, NULL);
    pthread_create(&threads[1], NULL, thread_do, NULL);
    pthread_detach(threads[0]);
    pthread_detach(threads[1]);
    sleep(1); // MAKING SURE THREADS HAVE INITIALIZED

    /* Kill threads */
    threads_keepalive = 0;
    sleep(5); // MAKING SURE THREADS HAVE UNBLOCKED
    free(threads);

    return 0;
}

运行该代码,虽然它是正确的(至少在我看来),但我会随机出现内存泄漏。我使用valgrind 多次运行相同的测试,如下所示

> gcc test.c -pthread -o test && for i in {1..100}; do valgrind --leak-check=full --track-origins=yes ./test 2>&1 | grep frees; done
==4088==   total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
==4211==   total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
==4337==   total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
==4463==   total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
==4590==   total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
==4717==   total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
==4853==   total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
==4981==   total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
==5110==   total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
==5239==   total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
..

发生了什么事??

更新:创建一个线程而不是两个线程不会显示内存泄漏。

【问题讨论】:

  • 好吧,首先你应该阅读 pthread_create() 的手册,特别是 thread_start() 的签名。
  • 没有thread_start()函数。你在说什么WTF?
  • 它在手册页上。在您的代码中,“thread_do()”应采用 void* 参数。我并不是说这肯定会对你的结果产生任何影响,但你是如此坚持以至于你检查了这么多东西......
  • 看,把 void* 放进去。大约需要 5 秒钟,然后一个可能的 UB 来源就被消灭了。
  • void* thread_do(void *param){...

标签: c memory-leaks pthreads valgrind


【解决方案1】:

你的问题的标题是错误的——你没有正确使用线程。但我不认为您的内存泄漏与您的任何未定义行为实例有关。这只是 valgrind 报告的虚假“泄漏”,原因是(假设您使用的是带有 glibc 的 Linux 系统)glibc 内部结构。请参阅以下相关问题:

【讨论】:

  • 那还有其他方法可以检查内存泄漏吗?
猜你喜欢
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-15
  • 1970-01-01
  • 1970-01-01
  • 2015-07-07
相关资源
最近更新 更多