如何在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