pthread导致的内存泄漏
memory leak caused by pthread
我正在用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);
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏