2014-01-22 56 views
0

如何在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)); 
+4

以正常方式使用'new'。你顯然做錯了,但由於你拒絕告訴我們你在做什麼,除了你可以診斷代碼中的錯誤。 –

+0

我正在使用多線程來列出目錄中的文件。我使用4個線程實現了它。但是在運行時顯示「堆損壞」之類的錯誤。我在網上衝浪,發現問題與內存有關。 – Baalki

+0

如果您需要更具體的答案,顯示錯誤和代碼可能會有所幫助。 – fritzone

回答

0

使用下面爲您的線程(僞代碼)的邏輯:

while (true) { 

    lock() 
    if (empty) { 
     unlock; 
     sleep; 
     continue; 
    } else { 
     get_one_dir; 
     remove_that_dir_from_list; 
     unlock; 
    } 
    process_the_dir; 
    continue; 
} 

對於鎖,使用Critical Section,當你想鎖定/再次解鎖在列表中推新的目錄。

讀取/寫入文件向量時使用相同的鎖定/解鎖邏輯。

+0

感謝您給出的邏輯....但它顯示「在目錄Listing.exe 0x76f68e19未處理的異常:0xC0000005:訪問衝突寫入位置0x00000014」。當達到lock()語句時發生此錯誤。 – Baalki

+0

請你可以提供一些更多的優化在邏輯中完成 – Baalki

0

用於訪問臨界區共享資源:
EnterCriticalSection(&my_section);
//perform data manipulation per-thread
LeaveCriticalSection(&my_section);

不要忘記使用前初始化的關鍵部分。
看到這個問題得到幫助Problems using EnterCriticalSection