有人可以向我解释一下为什么这个简单的代码会泄漏内存吗?
我相信,由于 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);
}
}
UPDATE:
我发现如果我在里面添加5毫秒的轻微延迟for
循环泄漏是WAY slower:
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 ///
}
This is freaking me out, could somebody please tell me what is happening? How this slight delay may produce such a significant change? (or alter the behavior in any way)
任何建议将不胜感激。
Thanks.
UPDATE2:
在 Windows 平台(W7 和 XP)上观察到此泄漏,在 Linux 平台上未观察到泄漏(谢谢@MichaelGoren)