pthread导致的内存泄漏

memory leak caused by pthread

本文关键字:内存 泄漏 pthread      更新时间:2023-10-16

我正在用c++做一个项目,我正在使用pthread。通过使用任务管理器,我可以注意到我的应用程序存在内存泄漏。

using namespace std;
int main()
{
while(true){
try{
Foo * foo = new Foo(args ...);
pthread_create(0,NULL,&Foo::doSomthing,NULL);
pthread_join(0 ,NULL);
delete foo;
}catch (const std::bad_alloc&) {
throw "";
}
Sleep(10);
system("cls");
}
return 0;
}

但如果我直接调用函数,内存泄漏就消失了

using namespace std;
int main()
{
while(true){
try{
Foo * foo = new Foo(args ...);
foo->doSomthing();
delete foo;
}catch (const std::bad_alloc&) {
throw "";           
}
Sleep(10);
system("cls");
}
return 0;
}

我已经将示例简化为

#include <pthread.h>
void* doSomthing(void *)
{
return NULL;
}
int main()
{
while (true)
{
pthread_create(0, NULL, doSomthing, NULL);
pthread_join(0, NULL);
}
return 0;
}

用户代码中没有内存分配。程序仍然泄漏。

CCD_ 1期望指向CCD_ 2的指针作为第一参数。此指针将用作不透明的pthread句柄,并根据pthread_create的内部实现进行初始化。我们不知道这里发生了什么。我们不需要知道。坦率地说,我们不想知道,因为这种信息破坏了抽象性,从而破坏了可移植性。

询问者的代码用0调用pthread_create。0将被视为NULL,这意味着pthread_create将对NULL指针进行操作。这就是经典的未定义行为。不要这样做。在Windows(具有g++4.8的MinGW(上,这似乎会导致线程运行、pthread_join失败(始终检查返回值!(和大量内存泄漏。在Linux中,这似乎会立即致命。

#include <pthread.h>
#include <iostream>
void* doSomthing(void *)
{
return NULL;
}
int main()
{
while (true)
{
pthread_t threadhandle;
if (!pthread_create(&threadhandle, NULL, doSomthing, NULL))
{
if (pthread_join(threadhandle, NULL))
{
std::cerr << "Join failn";
}
}
else
{
std::cerr << "Create failn";
}
}
return 0;
}

提供指向有效线程句柄的指针不会泄漏。检查和报告错误有助于调试和管理意外故障。第二种方法应该适用于您。

您将0作为第一个参数传递给pthread_join(),因此永远不会加入创建的线程。这就是你泄露内存的地方。

你需要加入你创建的线程:

pthread_t thread;
pthread_create(&thread, NULL, &Foo::doSomthing, NULL);
pthread_join(thread, NULL);