2012-05-07 73 views
0

任何人都可以幫助解決MFC應用程序中的內存泄漏問題嗎?該程序似乎沒有下面的代碼塊正常工作。該塊包括有條件地執行幾個任務和將數據傳遞給MFC對話框數據成員,然後更新MFC對話框上的指示符。其他測試顯示,除​​調試窗口中有內存泄漏消息外,一切正常。平臺:WIN 7 64bit,MSVC 2011.謝謝!使用線程的MFC應用程序中的內存泄漏

#include <vector> 
#include <thread> 

//Implementation parallel tasking 
void CMASTERDlg::OnCompositeParalleltasking() 
{ 
const int totTsk=8; 
BOOL select[totTsk]={ 
    m_Parallel_Audio, 
    m_Parallel_DDS, 
    m_Parallel_HV, 
    m_Parallel_Monitor, 
    m_Parallel_PDA, 
    m_Parallel_Pulnix, 
    m_Parallel_Supertime, 
    m_Parallel_Temp}; 

//Put all selected tasks in a thread vector 
std::vector<std::thread> threads; 
auto pvThread = threads.begin(); 

if (m_Parallel_Audio) 
    threads.push_back(std::thread(Audio, 1)); 
if (m_Parallel_DDS) 
    threads.push_back(std::thread(DDS, 1, 1)); 
if (m_Parallel_HV) 
    threads.push_back(std::thread(HVgetShow, this, 3)); 
if (m_Parallel_Monitor) 
    threads.push_back(std::thread(MonitorgetShow, this)); 
if (m_Parallel_PDA) 
    threads.push_back(std::thread(PDAgetShow, this)); 
if (m_Parallel_Pulnix) 
    threads.push_back(std::thread(DoNothing, 1)); 
if (m_Parallel_Supertime) 
    threads.push_back(std::thread(MMCS,Sequence_id, static_cast<LPCSTR>(CStringA(loopnum)))); 
if (m_Parallel_Temp) 
    threads.push_back(std::thread(TempgetShow,this)); 

pvThread = threads.begin(); 
while (pvThread != threads.end()) 
{ 
    pvThread->join(); 
    pvThread++; 
} 

//update data on front panel 
UpdateData(FALSE); 
UpdateWindow(); 


//count selected tasks and output message 
int j=0, count=0; 
for(j=0; j<totTsk; j++) { 
    if (select[j]) count++; 
} 
char buffer[2]; 
itoa (count,buffer,10); 
string message=string(buffer)+" tasks completed in parallel\n"; 
TRACE(message.c_str()); //Message in debugging window 

} 
+1

在發佈的代碼中似乎沒有任何內存分配,所以內存泄漏幾乎肯定會發生在您啓動的其中一個線程運行的某個函數中。 – Chad

+0

@ChadThanks乍得。我用下面的一個線程和一個簡單的無所事事函數測試了代碼,發現類似的內存泄漏,這讓我想知道我是否有任何設置錯誤。我很奇怪,在實施結束時我收到了一條消息,比預期的要早。 void DoNothing()//測試函數 { \t //什麼都不做 } – eLions

+0

它看起來像我添加的線程與MFC對話框的線程發生衝突。順便說一句,代碼塊可以在非GUI項目下運行就好了。 – eLions

回答

0

代碼

pvThread = threads.begin(); 
while (pvThread != threads.end()) 
{ 
    pvThread->join(); 
    pvThread++; 
} 

似乎值得商榷給我。第一次進入這個循環時,當前線程(我認爲是主應用程序UI線程)在第一個線程上調用join()時會阻塞,直到該線程完成。如果第一個線程比其他線程中的至少一部分花費更長的時間,那麼最終你會發現自己在一個不存在的線程上調用join()。處理這個問題時系統可能泄漏了什麼?

+0

謝謝pnswdv。這似乎很可能是問題所在。你有提示可以解決這個問題嗎?檢測到內存泄漏! 轉儲對象 - > {389} 0x00631518處的常規塊,長度爲56個字節。 Data:<> 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 對象轉儲完成。 – eLions

+1

如果有人感興趣,上面的問題可以通過MFC庫中的AfxBeginThread來解決,而不是直接使用線程。 – eLions