[英]Win32, MFC: Ending threads
我有一個DLL,它有一個名為CWork的基於CWinThread的類。 我使用AfxBeginThread創建它。
在這個類中,我定義了一個將infinet循環並執行某個任務的過程。 此過程將單獨用作線程。 我也使用AfxBeginThread創建它。
現在,當我的DLL退出時,我想結束線程。 這是因為我退出時遇到了崩潰,我很擔心這就是原因。
另外,還有
偽代碼示例:
Cmain類
Cmain::Cmain(){
pMyThread = AfxBeginThread(CWork - a CWinThread based Class);
}
UINT HandleNextVTSConnectionCommandProc(LPVOID pParam);
class CWork
CWork:CWork(){
AfxBeginThread(HandleNextVTSConnectionCommandProc, this);
}
UINT HandleNextVTSConnectionCommandProc(LPVOID pParam){
while(true){
dosomething();
sleep(2000);
}
}
我的問題是,結束這兩個線程的正確方法是什么?
謝謝!
一般來說,結束線程的正確方法是讓它完成,然后等待它完成。 因此,在Windows上,您可能會發出一個事件,要求線程完成,然后等待線程HANDLE。 強行終止一個線程幾乎總是一個被誤導的想法,它會回來困擾你。
創建一個最初未發信號的調用CreateEvent的事件。 當您的應用程序終止時,發出此事件的信號( SetEvent )並等待線程終止(線程句柄上的WaitForSingleObject )。
在你的線程函數HandleNextVTSConnectionCommandProc
你的while(true)
循環替換
while(WaitForSingleObject(hEvent, 0) != WAIT_OBJECT_0)
執行上述操作后,您可以通知您的應用程序終止線程。 當線程從其線程proc返回時,線程終止。
設置一個標志而不是使用while(true)來告訴你的線程何時結束。 你也可以使用一個事件。
您還應該在退出之前等待線程完成,因此您應該使用(在主代碼中,一旦您發出線程結束信號):
WaitForSingleObject(thread_handle)
這樣的事情應該讓你開始:
HANDLE g_hThreadExitRequest = NULL;
UINT __cdecl ThreadFunction(LPVOID pParam)
{
AllocConsole();
HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);
for (int i=1; true; ++i)
{
CStringA count;
count.Format("%d\n", i);
WriteFile(hCon, (LPCSTR)count, count.GetLength(), NULL, NULL);
if (WaitForSingleObject(g_hThreadExitRequest, 1000) == WAIT_OBJECT_0)
break;
}
// We can do any thread specific cleanup here.
FreeConsole();
return 0;
}
void Go()
{
// Create the event we use the request the thread exit.
g_hThreadExitRequest = CreateEvent(
NULL, // LPSECURITY_ATTRIBUTES lpEventAttributes
TRUE, // BOOL bManualReset
FALSE, // BOOL bInitialState
NULL // LPCTSTR lpName
);
// We create the thread suspended so we can mess with the returned CWinThread without
// MFC auto deleting it when the thread finishes.
CWinThread *pThread = AfxBeginThread(
&ThreadFunction, // AFX_THREADPROC pfnThreadProc
NULL, // LPVOID pParam
THREAD_PRIORITY_NORMAL, // int nPriority
0, // UINT nStackSize
CREATE_SUSPENDED , // DWORD dwCreateFlags
NULL // LPSECURITY_ATTRIBUTES lpSecurityAttrs
);
// Turn off MFC's auto delete "feature".
pThread->m_bAutoDelete = FALSE;
// Start the thread running.
pThread->ResumeThread();
// Wait 30 seconds.
Sleep(30*1000);
// Signal the thread to exit and wait for it to do so.
SetEvent(g_hThreadExitRequest);
WaitForSingleObject(pThread->m_hThread, INFINITE);
// Delete the CWinTread object since we turned off auto delete.
delete pThread;
// We're finished with the event.
CloseHandle(g_hThreadExitRequest);
g_hThreadExitRequest = NULL;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.