gpt4 book ai didi

c++ - 分离的 pthread 和内存泄漏

转载 作者:IT老高 更新时间:2023-10-28 23:02:56 27 4
gpt4 key购买 nike

谁能解释一下为什么这个简单的代码会泄漏内存?

我认为,由于 pthread 是在分离状态下创建的,因此它们的资源应该在终止后立即释放,但事实并非如此。

我的环境是Qt5.2。

#include <QCoreApplication>
#include <windows.h>

void *threadFunc( void *arg )
{
printf("#");
pthread_exit(NULL);
}

int main()
{
pthread_t thread;
pthread_attr_t attr;

while(1)
{
printf("\nStarting threads...\n");
for(int idx=0;idx<100;idx++)
{
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create( &thread, &attr, &threadFunc, NULL);
pthread_attr_destroy ( &attr );
}
printf("\nSleeping 10 seconds...\n");
Sleep(10000);
}
}

Memory leak graph

更新:

我发现如果我在 for 循环内添加 5 毫秒的轻微延迟,泄漏会WAY变慢:

    for(int idx=0;idx<100;idx++)
{
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create( &thread, &attr, &threadFunc, NULL);
pthread_attr_destroy ( &attr );
Sleep(5); /// <--- 5 MILLISECONDS DELAY ///
}

Memory leak graph with slight delay吓死我了,谁能告诉我这是怎么回事?这种轻微的延迟如何会产生如此重大的变化? (或以任何方式改变行为)

任何建议将不胜感激。

谢谢。

更新 2:

在 Windows 平台(W7 和 XP)上观察到此泄漏,在 Linux 平台上未观察到泄漏(谢谢@MichaelGoren)

最佳答案

我使用 cygwin 在 windows 上检查了该程序稍作修改,内存消耗稳定。所以肯定是qt问题; cygwin 上的 pthread 库可以正常工作而不会泄漏。

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>


void *threadFunc( void *arg )
{
printf("#");
pthread_exit(NULL);
}

int main()
{
pthread_t thread;
pthread_attr_t attr;
int idx;

while(1)
{
printf("\nStarting threads...\n");
for(idx=0;idx<100;idx++)
{
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create( &thread, &attr, &threadFunc, NULL);
pthread_attr_destroy ( &attr );
}
printf("\nSleeping 10 seconds...\n");
//Sleep(10000);
sleep(10);
}
}

关于c++ - 分离的 pthread 和内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21189328/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com