[英]Memory Allocation for threads in C++
如何在C ++中將內存顯式分配給線程? 我正在使用Windows API進行多線程處理。運行時,它有時會正確執行,但有時會顯示“堆損壞”,“未處理的異常”。請指導我
這是我創建線程的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));
使用關鍵部分訪問共享資源:
EnterCriticalSection(&my_section);
//perform data manipulation per-thread
LeaveCriticalSection(&my_section);
使用前,請不要忘記初始化關鍵部分。
請參閱此問題以獲取幫助使用EnterCriticalSection時遇到的問題
對線程使用以下邏輯(偽代碼):
while ( true ) {
lock()
if ( empty ) {
unlock;
sleep;
continue;
} else {
get_one_dir;
remove_that_dir_from_list;
unlock;
}
process_the_dir;
continue;
}
對於鎖定,請使用Critical Section
,然后在您要在列表中推送新目錄時再次鎖定/解鎖 。
讀取/寫入文件向量時使用相同的鎖定/解鎖邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.