在主线程用AfxBeginThread开启子线程时,偶尔会报内存泄漏的错误(单线程没问题)
不是频繁报,10次有1~2次的样子,debug我也不知道怎么跟踪,怀疑是锁的问题加上
CCriticalSection cs; cs.Lock();cs.Unlock();后发现还是不行,求助!
/*结构体*/
typedef struct _dlgTag
{
int nIdx;
CString strName;
} DLGTAG;
/*主线程代码*/
//初始化数组
m_Table.clear();
m_Table.swap(vector<vector<CString>>());
m_Table.resize(nLineCount);
for (int i = 0; i < nLineCount; i++)
{
m_Table[i].resize(3);
}
//遍历
nThreadNum = 0;
nThreadAll = 30;
for (int i = 0; i < nLineCount; i++)
{
//多线程工作
if (nThreadNum < nThreadAll)
{
DLGTAG *dd = new DLGTAG();
dd->nIdx = i;
dd->strName = strLine;
AfxBeginThread(LoopWorkThread, (LPVOID)dd);
nThreadNum++;
continue;
}
//轮巡线程池
while (1)
{
int nNull = 0, nBegin = i - nThreadAll, nEnd = i;
switch (nBegin)
{
case 0:
nBegin++;
nEnd++;
break;
default:
break;
}
for (int j = nBegin; j < nEnd; j++)
{
if (m_Table[j][1].IsEmpty())
{
nNull++;
Sleep(100);
}
}
//已完成数
if (nThreadAll - nNull > 0)
{
nThreadNum = nNull;
i--;
break;
}
}
}
//遍历结束检查线程是否全部执行完毕
while (1)
{
int nNull = 0, nDone = 0;
for (int i = 0; i < nLineCount; i++)
{
if (m_Table[i][1].IsEmpty())
{
nNull++;
Sleep(100);
}
}
nDone = nLineCount - nNull;
if (nDone >= nLineCount)
{
break;
}
}
/*子线程LoopWorkThread代码*/
CCriticalSection cs;
UINT LoopWorkThread(LPVOID pParam)
{
DLGTAG* dlg = (DLGTAG*)pParam;
CString strFlag = TestTest(dlg->nIdx, dlg->strName);
if (strFlag == "成功")
{
cs.Lock();
m_Table[dlg->nIdx][2] = 业务代码...
}
m_Table[dlg->nIdx][1] = strFlag;
cs.Unlock();
delete dlg;
return 0;
}