工作線程操作主界面控件引起死鎖及解決
問題描述:
在監控程序中,設計一監控循環。
頭文件.h
HANDLE m_hEventExit;
CWinThread* m_pThread;
構造函數中,創建該事件
m_hEventExit=CreateEvent(NULL, // 安全
TRUE, // 手動
FALSE, // 初始化為非信號模式
_T("Exit Event") // 線程名稱
);
在OnButtonThreadStart()中
{
if(!m_pThread)
{
ResetEvent(m_hEventExit);
m_ pThread = AfxBeginThread(MonitorThreadFunc, this);
}
}
MonitorThreadFunc 中需要修改主界面中的控件。
這時候如果在OnButtonThreadStop()中
{
SetEvent(m_hEventExit);
if(m_ pThread!= NULL)
{
TRACE0("The thread is still running.\n");
WaitForSingleObject(m_ pThread ->m_hThread, -1);
delete m_ pThread;
m_ pThread = NULL;
}
}
其中Wait行使主界面進入等待狀態,如果這時候工作線程執行完了,可以順利退出,如果線程此時正在更新界面控件,就會陷入死鎖。
解決方法:
使用WaitThreadWithHandleMsg函數,可以在等待線程結束的同時響應消息。
為了使用方便,將該函數封裝了一下,使用的時候只需要調用一下。

























































posted on 2009-02-12 22:15 岳陽 閱讀(2787) 評論(5) 編輯 收藏 引用 所屬分類: 『 VC&MFC 』