2011-07-01 100 views
1

所以線程終止,該代碼都在某種程度上是這樣的:C++與等待窗口

MAIN(){ 
/*waiting window class declaration*/ 
    threadinfo* oThread=new threadinfo(); //An object that will help me know when to finish the thread 
    QueueUserWorkItem((LPTHREAD_START_ROUTINE)waitingWindow, (void*)mThread, WT_EXECUTELONGFUNCTION); 
    function_that_takes_time(); 
    oThread->setTerminated(); //set member terminated to bool true 
/*continue with other things*/ 
} 

和waitingWindow功能,將在該線程

MSG msg; 
hwndWaiting=CreateWindow(...) // here the window is created 
while (msg.message != WM_QUIT) 
    { 
     if (PeekMessage(&msg, null, 0U, 0U, PM_REMOVE)) 
     { 
      TranslateMessage(&msg); 
      DispatchMessage(&msg); 
     } 
     else 
     { 
      if(oThread->isTerminated()) // isTerminated returns bool true if terminated 
      { 
       delete oThread; 
       ExitThread(0); 
      } 
     } 
    } 
ExitThread(0); 

潤了ExitThread刪除等待一個好辦法窗口,並安全地刪除線程? (至少我是100%肯定這種方式何時結束)。

我問這是因爲這部作品在Windows XP中很好,但將與「應用程序已停止工作」在Windows 7

感謝您的幫助崩潰。

+1

ExitThread是錯誤的。你知道嗎,在你的代碼中,它退出了我認爲不是你的意圖的調用線程。但是根本不要打電話。請求你的線程終止並等待,直到它結束。 –

+0

當你說「讓你的線程終止」時,我認爲你的意思是我仍然可以使用oThread並使用不同的函數來結束線程? (如_endThread())?或者返回一個值呢? – Filgera

+1

不可以。您向線索發送一條消息,告訴它您希望它終止。然後,您可以等到可以在方便的時候這樣做。 –

回答

3

一般來說結束線程的最好方法是讓它們「優雅地」完成自己。你可以告訴線程通過設置一個事件,例如結束:

HANDLE hevent_die = CreateEvent(...); 
HANDLE hthread_something = CreateThread(...); // or _beginthread() 
... 

DWORD WINAPI thread_func (LPVOID param) 
{ 
    while(working && WaitForSingleObject(hevent_die, 0)!=WAIT_OBJECT_0) 
    { 
    ... 
    } 

    return 0; 
} 


while (msg.message != WM_QUIT) 
{ 
    ... 

    if(WaitForSingleObject(hthread_something, 0) == WAIT_OBJECT_0) 
    { 
    // do things if needed 
    } 
} 

SetEvent(hevent_die); 
WaitForSingleObject(hthread_something, INFINITE); 

CloseHandle(hthread_something); 
CloseHandle(hevent_die); 
hthread_something = 0; 
hevent_die = 0; 

如果您正在使用的線程函數內部嵌套的循環,他們也將要結束,如果他們收到的事件。

+0

這看起來不錯。我會盡力瞭解這些事件,並會稍後回來報告。 – Filgera

3

你應該退出你的循環和乾淨的線程,以便正確調用任何析構函數。不要使用ExitThread(),只需使用一個標誌來指示何時退出循環,然後在最後退出waitWindow函數。