如何在C++中顯式地分配內存給線程?我正在使用Windows API進行多線程。雖然運行時有時會正確執行,但有時會顯示「堆損壞」,「未處理的異常」。請引導我C++中線程的內存分配
這是我創建線程的main()。
int main(int argc,char *argv[])
{
HANDLE hthread[MAX_THREADS];
//DWORD threadid;
FILETIME creation,exit,kernel,user;
SYSTEMTIME st1,st2;
//THREADENTRY32 entry;
char szEntrytime[255],szExittime[255];
directories.push_front(argv[1]);
files.clear();
Sem = CreateSemaphore(NULL,MAX_SEM_COUNT,MAX_SEM_COUNT,NULL);
if (Sem == NULL)
{
printf("CreateSemaphore error: %d\n", GetLastError());
return 1;
}
for(int i= 0;i<MAX_THREADS;i++)
{
hthread[i] = CreateThread(NULL,0,List,NULL,0,&threadid);
//hthread[i] = HeapAlloc(GetProcessHeap(),HEAP_NO_SERIALIZE,1024*30);
if(hthread[i] == NULL)
{
printf("CreateThread error: %d\n", GetLastError());
return 1;
}
}
內螺紋
while(!directories.empty())
{
string path = directories.front();
string spec = path + "\\" + "*";
WaitForSingleObject(Sem,0L);
directories.pop_front();
ReleaseSemaphore(Sem,1,NULL);
HANDLE hfind = FindFirstFileA(spec.c_str(),&ffd);
if(hfind == INVALID_HANDLE_VALUE)
continue;
cout<< path <<endl;;
do
{
if(strcmp(ffd.cFileName,".") && strcmp(ffd.cFileName,".."))
{
if(ffd.dwFileAttributes &FILE_ATTRIBUTE_DIRECTORY)
{
WaitForSingleObject(Sem,0L);
directories.push_front(path + "\\" + ffd.cFileName);
ReleaseSemaphore(Sem,1,NULL);
}
else
{
files.push_back(path + "\\" + ffd.cFileName);
Files++;
}
}
}while(FindNextFileA(hfind,&ffd));
以正常方式使用'new'。你顯然做錯了,但由於你拒絕告訴我們你在做什麼,除了你可以診斷代碼中的錯誤。 –
我正在使用多線程來列出目錄中的文件。我使用4個線程實現了它。但是在運行時顯示「堆損壞」之類的錯誤。我在網上衝浪,發現問題與內存有關。 – Baalki
如果您需要更具體的答案,顯示錯誤和代碼可能會有所幫助。 – fritzone