工作线程中调用MFC资源导致死锁

 

 

工作线程:

DWORD WINAPI CDecoder::DecodeThread(LPVOID pParam)
{
 while (ReadCouter<FileLen)
 {
  //判断标志,停止解码
  if (pDecoder->m_bDecodeExit)
  {
   File.Close();
   return 0;
  }
  
  do something
  
  //此处导致死锁
  //pDecoder->m_MsgWnd为静态文本框
  pDecoder->m_MsgWnd.SetWindowText(strTemp);

}

主线程:

开始线程:

 m_bDecodeExit=FALSE;
 m_pDecodeThread=::AfxBeginThread(
  (AFX_THREADPROC)DecodeThread,
  (LPVOID) this,
  THREAD_PRIORITY_NORMAL,
  CREATE_SUSPENDED,
  NULL
  );
 ASSERT_VALID(m_pDecodeThread);
 m_pDecodeThread-> ResumeThread();


结束线程:

 m_bDecodeExit=TRUE;
 if(WaitForSingleObject(m_pDecodeThread-> m_hThread,INFINITE)==WAIT_OBJECT_0)
 { 
  m_pDecodeThread=NULL;
 }
 
 
死锁原因分析:
主线程结束工作线程时使用WaitForSingleObject(m_pDecodeThread-> m_hThread,INFINITE)==WAIT_OBJECT_0
进入等待状态,如果此时工作线程执行pDecoder->m_MsgWnd.SetWindowText(strTemp)更改文本框,主线程将无法响应,
工作线程卡在pDecoder->m_MsgWnd.SetWindowText(strTemp),主线程一直等待从而死锁。
结论:
工作线程中避免操作MFC中与界面相关的函数。

 

2010-10-23

你可能感兴趣的:(thread,工作,object,null,mfc,winapi)