深入淺出Win32多執行緒程式設計--之MFC的多執行緒

Mobidogs發表於2020-04-04
1、建立和終止執行緒

  在MFC程式中建立一個執行緒,宜呼叫AfxBeginThread函式。該函式因引數不同而具有兩種過載版本,分別對應工作者執行緒和使用者介面(UI)執行緒。

  工作者執行緒

CWinThread *AfxBeginThread(
 AFX_THREADPROC pfnThreadProc, //控制函式
 LPVOID pParam, //傳遞給控制函式的引數
 int nPriority = THREAD_PRIORITY_NORMAL, //執行緒的優先順序
 UINT nStackSize = 0, //執行緒的堆疊大小
 DWORD dwCreateFlags = 0, //執行緒的建立標誌
 LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL //執行緒的安全屬性
);

  工作者執行緒程式設計較為簡單,只需編寫執行緒控制函式和啟動執行緒即可。下面的程式碼給出了定義一個控制函式和啟動它的過程:

//執行緒控制函式
UINT MfcThreadProc(LPVOID lpParam)
{
 CExampleClass *lpObject = (CExampleClass*)lpParam;
 if (lpObject == NULL || !lpObject->IsKindof(RUNTIME_CLASS(CExampleClass)))
  return - 1; //輸入引數非法
 //執行緒成功啟動
 while (1)
 {
  ...//
 }
 return 0;
}

//在MFC程式中啟動執行緒
AfxBeginThread(MfcThreadProc, lpObject);

  UI執行緒

  建立使用者介面執行緒時,必須首先從CWinThread 派生類,並使用 DECLARE_DYNCREATE 和 IMPLEMENT_DYNCREATE 巨集宣告此類。

  下面給出了CWinThread類的原型(新增了關於其重要函式功能和是否需要被繼承類過載的註釋):

class CWinThread : public CCmdTarget
{
 DECLARE_DYNAMIC(CWinThread)

 public:
  // Constructors
  CWinThread();
  BOOL CreateThread(DWORD dwCreateFlags = 0, UINT nStackSize = 0,
LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL);

  // Attributes
  CWnd* m_pMainWnd; // main window (usually same AfxGetApp()->m_pMainWnd)
  CWnd* m_pActiveWnd; // active main window (may not be m_pMainWnd)
  BOOL m_bAutoDelete; // enables 'delete this' after thread termination

  // only valid while running
  HANDLE m_hThread; // this thread's HANDLE
  operator HANDLE() const;
  DWORD m_nThreadID; // this thread's ID

  int GetThreadPriority();
  BOOL SetThreadPriority(int nPriority);

  // Operations
  DWORD SuspendThread();
  DWORD ResumeThread();
  BOOL PostThreadMessage(UINT message, WPARAM wParam, LPARAM lParam);

  // Overridables
  //執行執行緒例項初始化,必須重寫
  virtual BOOL InitInstance();

  // running and idle processing
  //控制執行緒的函式,包含訊息泵,一般不重寫
  virtual int Run();

  //訊息排程到TranslateMessage和DispatchMessage之前對其進行篩選,
  //通常不重寫
  virtual BOOL PreTranslateMessage(MSG* pMsg);

  virtual BOOL PumpMessage(); // low level message pump

  //執行執行緒特定的閒置時間處理,通常不重寫
  virtual BOOL OnIdle(LONG lCount); // return TRUE if more idle processing
  virtual BOOL IsIdleMessage(MSG* pMsg); // checks for special messages

  //執行緒終止時執行清除,通常需要重寫
  virtual int ExitInstance(); // default will 'delete this'

  //截獲由執行緒的訊息和命令處理程式引發的未處理異常,通常不重寫
  virtual LRESULT ProcessWndProcException(CException* e, const MSG* pMsg);

  // Advanced: handling messages sent to message filter hook
  virtual BOOL ProcessMessageFilter(int code, LPMSG lpMsg);

  // Advanced: virtual access to m_pMainWnd
  virtual CWnd* GetMainWnd();

  // Implementation
 public:
  virtual ~CWinThread();
  #ifdef _DEBUG
   virtual void AssertValid() const;
   virtual void Dump(CDumpContext& dc) const;
   int m_nDisablePumpCount; // Diagnostic trap to detect illegal re-entrancy
  #endif
  void CommonConstruct();
  virtual void Delete();
  // 'delete this' only if m_bAutoDelete == TRUE

  // message pump for Run
  MSG m_msgCur; // current message

 public:
  // constructor used by implementation of AfxBeginThread
  CWinThread(AFX_THREADPROC pfnThreadProc, LPVOID pParam);

  // valid after construction
  LPVOID m_pThreadParams; // generic parameters passed to starting function
  AFX_THREADPROC m_pfnThreadProc;

  // set after OLE is initialized
  void (AFXAPI* m_lpfnOleTermOrFreeLib)(BOOL, BOOL);
  COleMessageFilter* m_pMessageFilter;

 protected:
  CPoint m_ptCursorLast; // last mouse position
  UINT m_nMsgLast; // last mouse message
  BOOL DispatchThreadMessageEx(MSG* msg); // helper
  void DispatchThreadMessage(MSG* msg); // obsolete
};

  啟動UI執行緒的AfxBeginThread函式的原型為:

CWinThread *AfxBeginThread(
 //從CWinThread派生的類的 RUNTIME_CLASS
 CRuntimeClass *pThreadClass,
 int nPriority = THREAD_PRIORITY_NORMAL,
 UINT nStackSize = 0,
 DWORD dwCreateFlags = 0,
 LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL
);

  我們可以方便地使用VC++ 6.0類嚮導定義一個繼承自CWinThread的使用者執行緒類。下面給出產生我們自定義的CWinThread子類CMyUIThread的方法。

  開啟VC++ 6.0類嚮導,在如下視窗中選擇Base Class類為CWinThread,輸入子類名為CMyUIThread,點選"OK"按鈕後就產生了類CMyUIThread。


  其原始碼框架為:

/////////////////////////////////////////////////////////////////////////////
// CMyUIThread thread

class CMyUIThread : public CWinThread
{
 DECLARE_DYNCREATE(CMyUIThread)
 protected:
  CMyUIThread(); // protected constructor used by dynamic creation

  // Attributes
 public:

  // Operations
 public:

  // Overrides
  // ClassWizard generated virtual function overrides
  //{{AFX_VIRTUAL(CMyUIThread)
  public:
   virtual BOOL InitInstance();
   virtual int ExitInstance();
  //}}AFX_VIRTUAL

  // Implementation
 protected:
  virtual ~CMyUIThread();

  // Generated message map functions
  //{{AFX_MSG(CMyUIThread)
   // NOTE - the ClassWizard will add and remove member functions here.
  //}}AFX_MSG

 DECLARE_MESSAGE_MAP()
};

/////////////////////////////////////////////////////////////////////////////
// CMyUIThread

IMPLEMENT_DYNCREATE(CMyUIThread, CWinThread)

CMyUIThread::CMyUIThread()
{}

CMyUIThread::~CMyUIThread()
{}

BOOL CMyUIThread::InitInstance()
{
 // TODO: perform and per-thread initialization here
 return TRUE;
}

int CMyUIThread::ExitInstance()
{
 // TODO: perform any per-thread cleanup here
 return CWinThread::ExitInstance();
}

BEGIN_MESSAGE_MAP(CMyUIThread, CWinThread)
//{{AFX_MSG_MAP(CMyUIThread)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

  使用下列程式碼就可以啟動這個UI執行緒:

CMyUIThread *pThread;
pThread = (CMyUIThread*)
AfxBeginThread( RUNTIME_CLASS(CMyUIThread) );

  另外,我們也可以不用AfxBeginThread 建立執行緒,而是分如下兩步完成:

  (1)呼叫執行緒類的建構函式建立一個執行緒物件;

  (2)呼叫CWinThread::CreateThread函式來啟動該執行緒。

  線上程自身內呼叫AfxEndThread函式可以終止該執行緒:

void AfxEndThread(
 UINT nExitCode //the exit code of the thread
);


  對於UI執行緒而言,如果訊息佇列中放入了WM_QUIT訊息,將結束執行緒。

  關於UI執行緒和工作者執行緒的分配,最好的做法是:將所有與UI相關的操作放入主執行緒,其它的純粹的運算工作交給獨立的數個工作者執行緒。

  候捷先生早些時間喜歡為MDI程式的每個視窗建立一個執行緒,他後來澄清了這個錯誤。因為如果為MDI程式的每個視窗都單獨建立一個執行緒,在視窗進行切換的時候,將進行執行緒的上下文切換!
 

2.執行緒間通訊

  MFC中定義了繼承自CSyncObject類的CCriticalSection 、CCEvent、CMutex、CSemaphore類封裝和簡化了WIN32 API所提供的臨界區、事件、互斥和訊號量。使用這些同步機制,必須包含"Afxmt.h"標頭檔案。下圖給出了類的繼承關係:


  作為CSyncObject類的繼承類,我們僅僅使用基類CSyncObject的介面函式就可以方便、統一的操作CCriticalSection 、CCEvent、CMutex、CSemaphore類,下面是CSyncObject類的原型:

class CSyncObject : public CObject
{
 DECLARE_DYNAMIC(CSyncObject)

 // Constructor
 public:
  CSyncObject(LPCTSTR pstrName);

  // Attributes
 public:
  operator HANDLE() const;
  HANDLE m_hObject;

  // Operations
  virtual BOOL Lock(DWORD dwTimeout = INFINITE);
  virtual BOOL Unlock() = 0;
  virtual BOOL Unlock(LONG /* lCount */, LPLONG /* lpPrevCount=NULL */)
  { return TRUE; }

  // Implementation
 public:
  virtual ~CSyncObject();
  #ifdef _DEBUG
   CString m_strName;
   virtual void AssertValid() const;
   virtual void Dump(CDumpContext& dc) const;
  #endif
  friend class CSingleLock;
  friend class CMultiLock;
};

  CSyncObject類最主要的兩個函式是Lock和Unlock,若我們直接使用CSyncObject類及其派生類,我們需要非常小心地在Lock之後呼叫Unlock。

  MFC提供的另兩個類CSingleLock(等待一個物件)和CMultiLock(等待多個物件)為我們編寫應用程式提供了更靈活的機制,下面以實際來闡述CSingleLock的用法:

class CThreadSafeWnd
{
 public:
  CThreadSafeWnd(){}
  ~CThreadSafeWnd(){}
  void SetWindow(CWnd *pwnd)
  {
   m_pCWnd = pwnd;
  }
  void PaintBall(COLORREF color, CRect &rc);
 private:
  CWnd *m_pCWnd;
  CCriticalSection m_CSect;
};

void CThreadSafeWnd::PaintBall(COLORREF color, CRect &rc)
{
 CSingleLock csl(&m_CSect);
 //預設的Timeout是INFINITE,只有m_Csect被啟用,csl.Lock()才能返回
 //true,這裡一直等待
 if (csl.Lock())
;
 {
  // not necessary
  //AFX_MANAGE_STATE(AfxGetStaticModuleState( ));
  CDC *pdc = m_pCWnd->GetDC();
  CBrush brush(color);
  CBrush *oldbrush = pdc->SelectObject(&brush);
  pdc->Ellipse(rc);
  pdc->SelectObject(oldbrush);
  GdiFlush(); // don't wait to update the display
 }
}

  上述例項講述了用CSingleLock對Windows GDI相關物件進行保護的方法,下面再給出一個其他方面的例子:

int array1[10], array2[10];
CMutexSection section; //建立一個CMutex類的物件

//賦值執行緒控制函式
UINT EvaluateThread(LPVOID param)
{
 CSingleLock singlelock;
 singlelock(&section);

 //互斥區域
 singlelock.Lock();
 for (int i = 0; i < 10; i++)
  array1[i] = i;
 singlelock.Unlock();
}
//拷貝執行緒控制函式
UINT CopyThread(LPVOID param)
{
 CSingleLock singlelock;
 singlelock(&section);

 //互斥區域
 singlelock.Lock();
 for (int i = 0; i < 10; i++)
  array2[i] = array1[i];
 singlelock.Unlock();
}
}

AfxBeginThread(EvaluateThread, NULL); //啟動賦值執行緒
AfxBeginThread(CopyThread, NULL); //啟動拷貝執行緒

  上面的例子中啟動了兩個執行緒EvaluateThread和CopyThread,執行緒EvaluateThread把10個數賦值給陣列array1[],執行緒CopyThread將陣列array1[]拷貝給陣列array2[]。由於陣列的拷貝和賦值都是整體行為,如果不以互斥形式執行程式碼段:

for (int i = 0; i < 10; i++)
array1[i] = i;

  和

for (int i = 0; i < 10; i++)
array2[i] = array1[i];

  其結果是很難預料的!

  除了可使用CCriticalSection、CEvent、CMutex、CSemaphore作為執行緒間同步通訊的方式以外,我們還可以利用PostThreadMessage函式線上程間傳送訊息:

BOOL PostThreadMessage(DWORD idThread, // thread identifier
UINT Msg, // message to post
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
);

3.執行緒與訊息佇列

  在WIN32中,每一個執行緒都對應著一個訊息佇列。由於一個執行緒可以產生數個視窗,所以並不是每個視窗都對應著一個訊息佇列。下列幾句話應該作為"定理"被記住:

  "定理" 一

  所有產生給某個視窗的訊息,都先由建立這個視窗的執行緒處理;

  "定理" 二

  Windows螢幕上的每一個控制元件都是一個視窗,有對應的視窗函式。

  訊息的傳送通常有兩種方式,一是SendMessage,一是PostMessage,其原型分別為:

LRESULT SendMessage(HWND hWnd, // handle of destination window
 UINT Msg, // message to send
 WPARAM wParam, // first message parameter
 LPARAM lParam // second message parameter
);
BOOL PostMessage(HWND hWnd, // handle of destination window
 UINT Msg, // message to post
 WPARAM wParam, // first message parameter
 LPARAM lParam // second message parameter
);

  兩個函式原型中的四個引數的意義相同,但是SendMessage和PostMessage的行為有差異。SendMessage必須等待訊息被處理後才返回,而PostMessage僅僅將訊息放入訊息佇列。SendMessage的目標視窗如果屬於另一個執行緒,則會發生執行緒上下文切換,等待另一執行緒處理完成訊息。為了防止另一執行緒當掉,導致SendMessage永遠不能返回,我們可以呼叫SendMessageTimeout函式:

LRESULT SendMessageTimeout(
 HWND hWnd, // handle of destination window
 UINT Msg, // message to send
 WPARAM wParam, // first message parameter
 LPARAM lParam, // second message parameter
 UINT fuFlags, // how to send the message
 UINT uTimeout, // time-out duration
 LPDWORD lpdwResult // return value for synchronous call
);

  4. MFC執行緒、訊息佇列與MFC程式的"生死因果"

  分析MFC程式的主執行緒啟動及訊息佇列處理的過程將有助於我們進一步理解UI執行緒與訊息佇列的關係,為此我們需要簡單地敘述一下MFC程式的"生死因果"(侯捷:《深入淺出MFC》)。

  使用VC++ 6.0的嚮導完成一個最簡單的單文件架構MFC應用程式MFCThread:

  (1) 輸入MFC EXE工程名MFCThread;

  (2) 選擇單文件架構,不支援Document/View結構;

  (3) ActiveX、3D container等其他選項都選擇無。

  我們來分析這個工程。下面是產生的核心原始碼:

  MFCThread.h 檔案

class CMFCThreadApp : public CWinApp
{
 public:
  CMFCThreadApp();

  // Overrides
  // ClassWizard generated virtual function overrides
  //{{AFX_VIRTUAL(CMFCThreadApp)
   public:
    virtual BOOL InitInstance();
  //}}AFX_VIRTUAL

  // Implementation

 public:
  //{{AFX_MSG(CMFCThreadApp)
   afx_msg void OnAppAbout();
   // NOTE - the ClassWizard will add and remove member functions here.
   // DO NOT EDIT what you see in these blocks of generated code !
  //}}AFX_MSG
 DECLARE_MESSAGE_MAP()
};

  MFCThread.cpp檔案

CMFCThreadApp theApp;

/////////////////////////////////////////////////////////////////////////////
// CMFCThreadApp initialization

BOOL CMFCThreadApp::InitInstance()
{
 …
 CMainFrame* pFrame = new CMainFrame;
 m_pMainWnd = pFrame;

 // create and load the frame with its resources
 pFrame->LoadFrame(IDR_MAINFRAME,WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL,NULL);
 // The one and only window has been initialized, so show and update it.
 pFrame->ShowWindow(SW_SHOW);
 pFrame->UpdateWindow();

 return TRUE;
}

  MainFrm.h檔案

#include "ChildView.h"

class CMainFrame : public CFrameWnd
{
 public:
  CMainFrame();
 protected:
  DECLARE_DYNAMIC(CMainFrame)

  // Attributes
 public:

  // Operations
 public:
  // Overrides
  // ClassWizard generated virtual function overrides
  //{{AFX_VIRTUAL(CMainFrame)
   virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
   virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo);
  //}}AFX_VIRTUAL

  // Implementation
 public:
  virtual ~CMainFrame();
  #ifdef _DEBUG
   virtual void AssertValid() const;
   virtual void Dump(CDumpContext& dc) const;
  #endif
  CChildView m_wndView;

  // Generated message map functions
 protected:
 //{{AFX_MSG(CMainFrame)
  afx_msg void OnSetFocus(CWnd *pOldWnd);
  // NOTE - the ClassWizard will add and remove member functions here.
  // DO NOT EDIT what you see in these blocks of generated code!
 //}}AFX_MSG
 DECLARE_MESSAGE_MAP()
};

  MainFrm.cpp檔案

IMPLEMENT_DYNAMIC(CMainFrame, CFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
 //{{AFX_MSG_MAP(CMainFrame)
  // NOTE - the ClassWizard will add and remove mapping macros here.
  // DO NOT EDIT what you see in these blocks of generated code !
  ON_WM_SETFOCUS()
 //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction

CMainFrame::CMainFrame()
{
 // TODO: add member initialization code here
}

CMainFrame::~CMainFrame()
{}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
 if( !CFrameWnd::PreCreateWindow(cs) )
  return FALSE;
  // TODO: Modify the Window class or styles here by modifying
  // the CREATESTRUCT cs

 cs.dwExStyle &= ~WS_EX_CLIENTEDGE;
 cs.lpszClass = AfxRegisterWndClass(0);
 return TRUE;
}

  ChildView.h檔案

// CChildView window

class CChildView : public CWnd
{
 // Construction
 public:
  CChildView();

  // Attributes
 public:
  // Operations
 public:
  // Overrides
  // ClassWizard generated virtual function overrides
  //{{AFX_VIRTUAL(CChildView)
   protected:
    virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
  //}}AFX_VIRTUAL

  // Implementation
 public:
  virtual ~CChildView();

  // Generated message map functions
 protected:
  //{{AFX_MSG(CChildView)
   afx_msg void OnPaint();
  //}}AFX_MSG
 DECLARE_MESSAGE_MAP()
};

ChildView.cpp檔案
// CChildView

CChildView::CChildView()
{}

CChildView::~CChildView()
{}

BEGIN_MESSAGE_MAP(CChildView,CWnd )
//{{AFX_MSG_MAP(CChildView)
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CChildView message handlers

BOOL CChildView::PreCreateWindow(CREATESTRUCT& cs)
{
 if (!CWnd::PreCreateWindow(cs))
  return FALSE;

 cs.dwExStyle |= WS_EX_CLIENTEDGE;
 cs.style &= ~WS_BORDER;
 cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS,::LoadCursor(NULL, IDC_ARROW),
HBRUSH(COLOR_WINDOW+1),NULL);

 return TRUE;
}

void CChildView::OnPaint()
{
 CPaintDC dc(this); // device context for painting

 // TODO: Add your message handler code here
 // Do not call CWnd::OnPaint() for painting messages
}

  檔案MFCThread.h和MFCThread.cpp定義和實現的類CMFCThreadApp繼承自CWinApp類,而CWinApp類又繼承自CWinThread類(CWinThread類又繼承自CCmdTarget類),所以CMFCThread本質上是一個MFC執行緒類,下圖給出了相關的類層次結構:

我們提取CWinApp類原型的一部分:

class CWinApp : public CWinThread
{
 DECLARE_DYNAMIC(CWinApp)
 public:
  // Constructor
  CWinApp(LPCTSTR lpszAppName = NULL);// default app name
  // Attributes
  // Startup args (do not change)
  HINSTANCE m_hInstance;
  HINSTANCE m_hPrevInstance;
  LPTSTR m_lpCmdLine;
  int m_nCmdShow;
  // Running args (can be changed in InitInstance)
  LPCTSTR m_pszAppName; // human readable name
  LPCTSTR m_pszExeName; // executable name (no spaces)
  LPCTSTR m_pszHelpFilePath; // default based on module path
  LPCTSTR m_pszProfileName; // default based on app name

  // Overridables
  virtual BOOL InitApplication();
  virtual BOOL InitInstance();
  virtual int ExitInstance(); // return app exit code
  virtual int Run();
  virtual BOOL OnIdle(LONG lCount); // return TRUE if more idle processing
  virtual LRESULT ProcessWndProcException(CException* e,const MSG* pMsg);

 public:
  virtual ~CWinApp();
 protected:
  DECLARE_MESSAGE_MAP()
};

  SDK程式的WinMain 所完成的工作現在由CWinApp 的三個函式完成:

virtual BOOL InitApplication();
virtual BOOL InitInstance();
virtual int Run();

  "CMFCThreadApp theApp;"語句定義的全域性變數theApp是整個程式的application object,每一個MFC 應用程式都有一個。當我們執行MFCThread程式的時候,這個全域性變數被構造。theApp 配置完成後,WinMain開始執行。但是程式中並沒有WinMain的程式碼,它在哪裡呢?原來MFC早已準備好並由Linker直接加到應用程式程式碼中的,其原型為(存在於VC++6.0安裝目錄下提供的APPMODUL.CPP檔案中):

extern "C" int WINAPI
_tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow)
{
 // call shared/exported WinMain
 return AfxWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
}

  其中呼叫的AfxWinMain如下(存在於VC++6.0安裝目錄下提供的WINMAIN.CPP檔案中):

int AFXAPI AfxWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow)
{
 ASSERT(hPrevInstance == NULL);

 int nReturnCode = -1;
 CWinThread* pThread = AfxGetThread();
 CWinApp* pApp = AfxGetApp();

 // AFX internal initialization
 if (!AfxWinInit(hInstance, hPrevInstance, lpCmdLine, nCmdShow))
  goto InitFailure;

 // App global initializations (rare)
 if (pApp != NULL && !pApp->InitApplication())
  goto InitFailure;

 // Perform specific initializations
 if (!pThread->InitInstance())
 {
  if (pThread->m_pMainWnd != NULL)
  {
   TRACE0("Warning: Destroying non-NULL m_pMainWnd/n");
   pThread->m_pMainWnd->DestroyWindow();
  }
  nReturnCode = pThread->ExitInstance();
  goto InitFailure;
 }
 nReturnCode = pThread->Run();

 InitFailure:
 #ifdef _DEBUG
  // Check for missing AfxLockTempMap calls
  if (AfxGetModuleThreadState()->m_nTempMapLock != 0)
  {
   TRACE1("Warning: Temp map lock count non-zero (%ld)./n",
AfxGetModuleThreadState()->m_nTempMapLock);
  }
  AfxLockTempMaps();
  AfxUnlockTempMaps(-1);
 #endif

 AfxWinTerm();
 return nReturnCode;
}

  我們提取主幹,實際上,這個函式做的事情主要是:

CWinThread* pThread = AfxGetThread();
CWinApp* pApp = AfxGetApp();
AfxWinInit(hInstance, hPrevInstance, lpCmdLine, nCmdShow)
pApp->InitApplication()
pThread->InitInstance()
pThread->Run();

  其中,InitApplication 是註冊視窗類別的場所;InitInstance是產生視窗並顯示視窗的場所;Run是提取並分派訊息的場所。這樣,MFC就同WIN32 SDK程式對應起來了。CWinThread::Run是程式生命的"活水源頭"(侯捷:《深入淺出MFC》,函式存在於VC++ 6.0安裝目錄下提供的THRDCORE.CPP檔案中):

// main running routine until thread exits
int CWinThread::Run()
{
 ASSERT_VALID(this);

 // for tracking the idle time state
 BOOL bIdle = TRUE;
 LONG lIdleCount = 0;

 // acquire and dispatch messages until a WM_QUIT message is received.
 for (;;)
 {
  // phase1: check to see if we can do idle work
  while (bIdle && !::PeekMessage(&m_msgCur, NULL, NULL, NULL, PM_NOREMOVE))
  {
   // call OnIdle while in bIdle state
   if (!OnIdle(lIdleCount++))
    bIdle = FALSE; // assume "no idle" state
  }

  // phase2: pump messages while available
  do
  {
   // pump message, but quit on WM_QUIT
   if (!PumpMessage())
    return ExitInstance();

   // reset "no idle" state after pumping "normal" message
   if (IsIdleMessage(&m_msgCur))
   {
    bIdle = TRUE;
    lIdleCount = 0;
   }

  } while (::PeekMessage(&m_msgCur, NULL, NULL, NULL, PM_NOREMOVE));
 }
 ASSERT(FALSE); // not reachable
}

  其中的PumpMessage函式又對應於:

/////////////////////////////////////////////////////////////////////////////
// CWinThread implementation helpers

BOOL CWinThread::PumpMessage()
{
 ASSERT_VALID(this);

 if (!::GetMessage(&m_msgCur, NULL, NULL, NULL))
 {
  return FALSE;
 }

 // process this message
 if(m_msgCur.message != WM_KICKIDLE && !PreTranslateMessage(&m_msgCur))
 {
  ::TranslateMessage(&m_msgCur);
  ::DispatchMessage(&m_msgCur);
 }
 return TRUE;
}

  因此,忽略IDLE狀態,整個RUN的執行提取主幹就是:

do {
 ::GetMessage(&msg,...);
 PreTranslateMessage{&msg);
 ::TranslateMessage(&msg);
 ::DispatchMessage(&msg);
 ...
} while (::PeekMessage(...));

  由此,我們建立了MFC訊息獲取和派生機制與WIN32 SDK程式之間的對應關係。下面繼續分析MFC訊息的"繞行"過程。

  在MFC中,只要是CWnd 衍生類別,就可以攔下任何Windows訊息。與視窗無關的MFC類別(例如CDocument 和CWinApp)如果也想處理訊息,必須衍生自CCmdTarget,並且只可能收到WM_COMMAND訊息。所有能進行MESSAGE_MAP的類都繼承自CCmdTarget,如:


  MFC中MESSAGE_MAP的定義依賴於以下三個巨集:

DECLARE_MESSAGE_MAP()

BEGIN_MESSAGE_MAP(
 theClass, //Specifies the name of the class whose message map this is
 baseClass //Specifies the name of the base class of theClass
)

END_MESSAGE_MAP()

  我們程式中涉及到的有:MFCThread.h、MainFrm.h、ChildView.h檔案

DECLARE_MESSAGE_MAP()
MFCThread.cpp檔案
BEGIN_MESSAGE_MAP(CMFCThreadApp, CWinApp)
//{{AFX_MSG_MAP(CMFCThreadApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
MainFrm.cpp檔案
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code !
ON_WM_SETFOCUS()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
ChildView.cpp檔案
BEGIN_MESSAGE_MAP(CChildView,CWnd )
//{{AFX_MSG_MAP(CChildView)
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

  由這些巨集,MFC建立了一個訊息對映表(訊息流動網),按照訊息流動網匹配對應的訊息處理函式,完成整個訊息的"繞行"。

  看到這裡相信你有這樣的疑問:程式定義了CWinApp類的theApp全域性變數,可是從來沒有呼叫AfxBeginThread或theApp.CreateThread啟動執行緒呀,theApp對應的執行緒是怎麼啟動的?

  答:MFC在這裡用了很高明的一招。實際上,程式開始執行,第一個執行緒是由作業系統(OS)啟動的,在CWinApp的建構函式裡,MFC將theApp"對應"向了這個執行緒,具體的實現是這樣的:

CWinApp::CWinApp(LPCTSTR lpszAppName)
{
 if (lpszAppName != NULL)
  m_pszAppName = _tcsdup(lpszAppName);
 else
  m_pszAppName = NULL;

 // initialize CWinThread state
 AFX_MODULE_STATE *pModuleState = _AFX_CMDTARGET_GETSTATE();
 AFX_MODULE_THREAD_STATE *pThreadState = pModuleState->m_thread;
 ASSERT(AfxGetThread() == NULL);
 pThreadState->m_pCurrentWinThread = this;
 ASSERT(AfxGetThread() == this);
 m_hThread = ::GetCurrentThread();
 m_nThreadID = ::GetCurrentThreadId();

 // initialize CWinApp state
 ASSERT(afxCurrentWinApp == NULL); // only one CWinApp object please
 pModuleState->m_pCurrentWinApp = this;
 ASSERT(AfxGetApp() == this);

 // in non-running state until WinMain
 m_hInstance = NULL;
 m_pszHelpFilePath = NULL;
 m_pszProfileName = NULL;
 m_pszRegistryKey = NULL;
 m_pszExeName = NULL;
 m_pRecentFileList = NULL;
 m_pDocManager = NULL;
 m_atomApp = m_atomSystemTopic = NULL; //微軟懶鬼?或者他認為
 //這樣連等含義更明確?
 m_lpCmdLine = NULL;
 m_pCmdInfo = NULL;

 // initialize wait cursor state
 m_nWaitCursorCount = 0;
 m_hcurWaitCursorRestore = NULL;

 // initialize current printer state
 m_hDevMode = NULL;
 m_hDevNames = NULL;
 m_nNumPreviewPages = 0; // not specified (defaults to 1)

 // initialize DAO state
 m_lpfnDaoTerm = NULL; // will be set if AfxDaoInit called

 // other initialization
 m_bHelpMode = FALSE;
 m_nSafetyPoolSize = 512; // default size
}

  很顯然,theApp成員變數都被賦予OS啟動的這個當前執行緒相關的值,如程式碼:

m_hThread = ::GetCurrentThread();//theApp的執行緒控制程式碼等於當前執行緒控制程式碼
m_nThreadID = ::GetCurrentThreadId();//theApp的執行緒ID等於當前執行緒ID

  所以CWinApp類幾乎只是為MFC程式的第一個執行緒量身定製的,它不需要也不能被AfxBeginThread或theApp.CreateThread"再次"啟動。這就是CWinApp類和theApp全域性變數的內涵!如果你要再增加一個UI執行緒,不要繼承類CWinApp,而應繼承類CWinThread。而參考第1節,由於我們一般以主執行緒(在MFC程式裡實際上就是OS啟動的第一個執行緒)處理所有視窗的訊息,所以我們幾乎沒有再啟動UI執行緒的需求!

相關文章