您的位置:首页 > 其它

线程创建时内存注意释放

2014-08-18 11:24 176 查看
情况:近来学习之前的老代码,发现 申请内存 ,然后指针传给线程的回调函数中, 但是一直都没有找到释放的地方。。 所以写下面小demo 学习下。。

#include "stdafx.h"
#include<iostream>
#include <atlstr.h>

#include <iostream>
using namespace std;

DWORD WINAPI testThreadProc(LPVOID lpParameter)
{
if (NULL != lpParameter)
{
delete [] lpParameter; // 若是注释掉这一句,在任务管理器中会看到内存在不断的上升。。
lpParameter = NULL;
}

cout << " test thread End.." << endl;
return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
DWORD dwThreadId;

for (int i = 0; i < 20; ++i)
{
int* pInt = new int[1000 * 10000];

if (NULL == pInt)
{
cout << "Allocate Memory Failed.. " << endl;
break;
}

HANDLE hThread = CreateThread(NULL, 1024 * 1024 * 20, testThreadProc, pInt, 0, &dwThreadId);

if (NULL == hThread)
{
cout << "Create Thread Failed..." << endl;

// 注意线程创建失败也把内存给释放掉
if (NULL != pInt)
{
delete [] pInt;
pInt = NULL;
}
}
else
{
cout << "Create Thread Successed..." << endl;
}

Sleep(1000); // 便于观察
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: