深入淺出Win32多線程設(shè)計(jì)之MFC的多線程(ZT)
1、創(chuàng)建和終止線程 在MFC程序中創(chuàng)建一個(gè)線程,宜調(diào)用AfxBeginThread函數(shù)。該函數(shù)因參數(shù)不同而具有兩種重載版本,分別對(duì)應(yīng)工作者線程和用戶(hù)接口(UI)線程。 工作者線程 CWinThread *AfxBeginThread( AFX_THREADPROC pfnThreadProc, //控制函數(shù) LPVOID pParam, //傳遞給控制函數(shù)的參數(shù) int nPriority = THREAD_PRIORITY_NORMAL, //線程的優(yōu)先級(jí) UINT nStackSize = 0, //線程的堆棧大小 DWORD dwCreateFlags = 0, //線程的創(chuàng)建標(biāo)志 LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL //線程的安全屬性 ); |
工作者線程編程較為簡(jiǎn)單,只需編寫(xiě)線程控制函數(shù)和啟動(dòng)線程即可。下面的代碼給出了定義一個(gè)控制函數(shù)和啟動(dòng)它的過(guò)程: //線程控制函數(shù) UINT MfcThreadProc(LPVOID lpParam) { CExampleClass *lpObject = (CExampleClass*)lpParam; if (lpObject == NULL || !lpObject->IsKindof(RUNTIME_CLASS(CExampleClass))) return - 1; //輸入?yún)?shù)非法 //線程成功啟動(dòng) while (1) { ...// } return 0; }
//在MFC程序中啟動(dòng)線程 AfxBeginThread(MfcThreadProc, lpObject); |
UI線程 創(chuàng)建用戶(hù)界面線程時(shí),必須首先從CWinThread 派生類(lèi),并使用 DECLARE_DYNCREATE 和 IMPLEMENT_DYNCREATE 宏聲明此類(lèi)。 下面給出了CWinThread類(lèi)的原型(添加了關(guān)于其重要函數(shù)功能和是否需要被繼承類(lèi)重載的注釋?zhuān)?br /> 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 //執(zhí)行線程實(shí)例初始化,必須重寫(xiě) virtual BOOL InitInstance();
// running and idle processing //控制線程的函數(shù),包含消息泵,一般不重寫(xiě) virtual int Run();
//消息調(diào)度到TranslateMessage和DispatchMessage之前對(duì)其進(jìn)行篩選, //通常不重寫(xiě) virtual BOOL PreTranslateMessage(MSG* pMsg);
virtual BOOL PumpMessage(); // low level message pump
//執(zhí)行線程特定的閑置時(shí)間處理,通常不重寫(xiě) virtual BOOL OnIdle(LONG lCount); // return TRUE if more idle processing virtual BOOL IsIdleMessage(MSG* pMsg); // checks for special messages
//線程終止時(shí)執(zhí)行清除,通常需要重寫(xiě) virtual int ExitInstance(); // default will 'delete this'
//截獲由線程的消息和命令處理程序引發(fā)的未處理異常,通常不重寫(xiě) 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 };
|
啟動(dòng)UI線程的AfxBeginThread函數(shù)的原型為: CWinThread *AfxBeginThread( //從CWinThread派生的類(lèi)的 RUNTIME_CLASS CRuntimeClass *pThreadClass, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL ); |
我們可以方便地使用VC++ 6.0類(lèi)向?qū)Фx一個(gè)繼承自CWinThread的用戶(hù)線程類(lèi)。下面給出產(chǎn)生我們自定義的CWinThread子類(lèi)CMyUIThread的方法。 打開(kāi)VC++ 6.0類(lèi)向?qū)В谌缦麓翱谥羞x擇Base Class類(lèi)為CWinThread,輸入子類(lèi)名為CMyUIThread,點(diǎn)擊"OK"按鈕后就產(chǎn)生了類(lèi)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() |
使用下列代碼就可以啟動(dòng)這個(gè)UI線程: CMyUIThread *pThread; pThread = (CMyUIThread*) AfxBeginThread( RUNTIME_CLASS(CMyUIThread) ); |
另外,我們也可以不用AfxBeginThread 創(chuàng)建線程,而是分如下兩步完成: (1)調(diào)用線程類(lèi)的構(gòu)造函數(shù)創(chuàng)建一個(gè)線程對(duì)象; (2)調(diào)用CWinThread::CreateThread函數(shù)來(lái)啟動(dòng)該線程。 在線程自身內(nèi)調(diào)用AfxEndThread函數(shù)可以終止該線程: void AfxEndThread( UINT nExitCode //the exit code of the thread ); |
對(duì)于UI線程而言,如果消息隊(duì)列中放入了WM_QUIT消息,將結(jié)束線程。 關(guān)于UI線程和工作者線程的分配,最好的做法是:將所有與UI相關(guān)的操作放入主線程,其它的純粹的運(yùn)算工作交給獨(dú)立的數(shù)個(gè)工作者線程。 候捷先生早些時(shí)間喜歡為MDI程序的每個(gè)窗口創(chuàng)建一個(gè)線程,他后來(lái)澄清了這個(gè)錯(cuò)誤。因?yàn)槿绻麨镸DI程序的每個(gè)窗口都單獨(dú)創(chuàng)建一個(gè)線程,在窗口進(jìn)行切換的時(shí)候,將進(jìn)行線程的上下文切換!
2.線程間通信 MFC中定義了繼承自CSyncObject類(lèi)的CCriticalSection
、CCEvent、CMutex、CSemaphore類(lèi)封裝和簡(jiǎn)化了WIN32
API所提供的臨界區(qū)、事件、互斥和信號(hào)量。使用這些同步機(jī)制,必須包含"Afxmt.h"頭文件。下圖給出了類(lèi)的繼承關(guān)系: 作為CSyncObject類(lèi)的繼承類(lèi),我們僅僅使用基類(lèi)CSyncObject的接口函數(shù)就可以方便、統(tǒng)一的操作CCriticalSection 、CCEvent、CMutex、CSemaphore類(lèi),下面是CSyncObject類(lèi)的原型: 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類(lèi)最主要的兩個(gè)函數(shù)是Lock和Unlock,若我們直接使用CSyncObject類(lèi)及其派生類(lèi),我們需要非常小心地在Lock之后調(diào)用Unlock。 MFC提供的另兩個(gè)類(lèi)CSingleLock(等待一個(gè)對(duì)象)和CMultiLock(等待多個(gè)對(duì)象)為我們編寫(xiě)應(yīng)用程序提供了更靈活的機(jī)制,下面以實(shí)際來(lái)闡述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 } } |
上述實(shí)例講述了用CSingleLock對(duì)Windows GDI相關(guān)對(duì)象進(jìn)行保護(hù)的方法,下面再給出一個(gè)其他方面的例子: int array1[10], array2[10]; CMutexSection section; //創(chuàng)建一個(gè)CMutex類(lèi)的對(duì)象
//賦值線程控制函數(shù) UINT EvaluateThread(LPVOID param) { CSingleLock singlelock; singlelock(§ion);
//互斥區(qū)域 singlelock.Lock(); for (int i = 0; i < 10; i++) array1[i] = i; singlelock.Unlock(); } //拷貝線程控制函數(shù) UINT CopyThread(LPVOID param) { CSingleLock singlelock; singlelock(§ion);
//互斥區(qū)域 singlelock.Lock(); for (int i = 0; i < 10; i++) array2[i] = array1[i]; singlelock.Unlock(); } }
AfxBeginThread(EvaluateThread, NULL); //啟動(dòng)賦值線程 AfxBeginThread(CopyThread, NULL); //啟動(dòng)拷貝線程 |
上面的例子中啟動(dòng)了兩個(gè)線程EvaluateThread和CopyThread,線程EvaluateThread把10個(gè)數(shù)賦值給數(shù)組array1
[],線程CopyThread將數(shù)組array1[]拷貝給數(shù)組array2[]。由于數(shù)組的拷貝和賦值都是整體行為,如果不以互斥形式執(zhí)行代碼段: for (int i = 0; i < 10; i++) array1[i] = i; |
和 for (int i = 0; i < 10; i++) array2[i] = array1[i]; |
其結(jié)果是很難預(yù)料的! 除了可使用CCriticalSection、CEvent、CMutex、CSemaphore作為線程間同步通信的方式以外,我們還可以利用PostThreadMessage函數(shù)在線程間發(fā)送消息: BOOL PostThreadMessage(DWORD idThread, // thread identifier UINT Msg, // message to post WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); |
3.線程與消息隊(duì)列 在WIN32中,每一個(gè)線程都對(duì)應(yīng)著一個(gè)消息隊(duì)列。由于一個(gè)線程可以產(chǎn)生數(shù)個(gè)窗口,所以并不是每個(gè)窗口都對(duì)應(yīng)著一個(gè)消息隊(duì)列。下列幾句話應(yīng)該作為"定理"被記住: "定理" 一 所有產(chǎn)生給某個(gè)窗口的消息,都先由創(chuàng)建這個(gè)窗口的線程處理; "定理" 二 Windows屏幕上的每一個(gè)控件都是一個(gè)窗口,有對(duì)應(yīng)的窗口函數(shù)。 消息的發(fā)送通常有兩種方式,一是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 ); |
兩個(gè)函數(shù)原型中的四個(gè)參數(shù)的意義相同,但是SendMessage和PostMessage的行為有差異。SendMessage必須等待消息被處理后
才返回,而PostMessage僅僅將消息放入消息隊(duì)列。SendMessage的目標(biāo)窗口如果屬于另一個(gè)線程,則會(huì)發(fā)生線程上下文切換,等待另一線程
處理完成消息。為了防止另一線程當(dāng)?shù)簦瑢?dǎo)致SendMessage永遠(yuǎn)不能返回,我們可以調(diào)用SendMessageTimeout函數(shù): 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線程、消息隊(duì)列與MFC程序的"生死因果" 分析MFC程序的主線程啟動(dòng)及消息隊(duì)列處理的過(guò)程將有助于我們進(jìn)一步理解UI線程與消息隊(duì)列的關(guān)系,為此我們需要簡(jiǎn)單地?cái)⑹鲆幌翸FC程序的"生死因果"(侯捷:《深入淺出MFC》)。 使用VC++ 6.0的向?qū)瓿梢粋€(gè)最簡(jiǎn)單的單文檔架構(gòu)MFC應(yīng)用程序MFCThread: (1) 輸入MFC EXE工程名MFCThread; (2) 選擇單文檔架構(gòu),不支持Document/View結(jié)構(gòu); (3) ActiveX、3D container等其他選項(xiàng)都選擇無(wú)。 我們來(lái)分析這個(gè)工程。下面是產(chǎn)生的核心源代碼: 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定義和實(shí)現(xiàn)的類(lèi)CMFCThreadApp繼承自CWinApp類(lèi),而CWinApp類(lèi)又繼承
自CWinThread類(lèi)(CWinThread類(lèi)又繼承自CCmdTarget類(lèi)),所以CMFCThread本質(zhì)上是一個(gè)MFC線程類(lèi),下圖給出了相
關(guān)的類(lèi)層次結(jié)構(gòu):
我們提取CWinApp類(lèi)原型的一部分: 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 所完成的工作現(xiàn)在由CWinApp 的三個(gè)函數(shù)完成: virtual BOOL InitApplication(); virtual BOOL InitInstance(); virtual int Run(); |
"CMFCThreadApp theApp;"語(yǔ)句定義的全局變量theApp是整個(gè)程式的application object,每一個(gè)MFC
應(yīng)用程序都有一個(gè)。當(dāng)我們執(zhí)行MFCThread程序的時(shí)候,這個(gè)全局變量被構(gòu)造。theApp
配置完成后,WinMain開(kāi)始執(zhí)行。但是程序中并沒(méi)有WinMain的代碼,它在哪里呢?原來(lái)MFC早已準(zhǔn)備好并由Linker直接加到應(yīng)用程序代碼中
的,其原型為(存在于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); } |
其中調(diào)用的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; } |
我們提取主干,實(shí)際上,這個(gè)函數(shù)做的事情主要是: CWinThread* pThread = AfxGetThread(); CWinApp* pApp = AfxGetApp(); AfxWinInit(hInstance, hPrevInstance, lpCmdLine, nCmdShow) pApp->InitApplication() pThread->InitInstance() pThread->Run(); |
其中,InitApplication
是注冊(cè)窗口類(lèi)別的場(chǎng)所;InitInstance是產(chǎn)生窗口并顯示窗口的場(chǎng)所;Run是提取并分派消息的場(chǎng)所。這樣,MFC就同WIN32
SDK程序?qū)?yīng)起來(lái)了。CWinThread::Run是程序生命的"活水源頭"(侯捷:《深入淺出MFC》,函數(shù)存在于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函數(shù)又對(duì)應(yīng)于: ///////////////////////////////////////////////////////////////////////////// // 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狀態(tài),整個(gè)RUN的執(zhí)行提取主干就是: do { ::GetMessage(&msg,...); PreTranslateMessage{&msg); ::TranslateMessage(&msg); ::DispatchMessage(&msg); ... } while (::PeekMessage(...)); |
由此,我們建立了MFC消息獲取和派生機(jī)制與WIN32 SDK程序之間的對(duì)應(yīng)關(guān)系。下面繼續(xù)分析MFC消息的"繞行"過(guò)程。
在MFC中,只要是CWnd 衍生類(lèi)別,就可以攔下任何Windows消息。與窗口無(wú)關(guān)的MFC類(lèi)別(例如CDocument
和CWinApp)如果也想處理消息,必須衍生自CCmdTarget,并且只可能收到WM_COMMAND消息。所有能進(jìn)行MESSAGE_MAP的類(lèi)
都繼承自CCmdTarget,如: MFC中MESSAGE_MAP的定義依賴(lài)于以下三個(gè)宏: 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建立了一個(gè)消息映射表(消息流動(dòng)網(wǎng)),按照消息流動(dòng)網(wǎng)匹配對(duì)應(yīng)的消息處理函數(shù),完成整個(gè)消息的"繞行"。 看到這里相信你有這樣的疑問(wèn):程序定義了CWinApp類(lèi)的theApp全局變量,可是從來(lái)沒(méi)有調(diào)用AfxBeginThread或theApp.CreateThread啟動(dòng)線程呀,theApp對(duì)應(yīng)的線程是怎么啟動(dòng)的? 答:MFC在這里用了很高明的一招。實(shí)際上,程序開(kāi)始運(yùn)行,第一個(gè)線程是由操作系統(tǒng)(OS)啟動(dòng)的,在CWinApp的構(gòu)造函數(shù)里,MFC將theApp"對(duì)應(yīng)"向了這個(gè)線程,具體的實(shí)現(xiàn)是這樣的: 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; //微軟懶鬼?或者他認(rèn)為 //這樣連等含義更明確? 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啟動(dòng)的這個(gè)當(dāng)前線程相關(guān)的值,如代碼: m_hThread = ::GetCurrentThread();//theApp的線程句柄等于當(dāng)前線程句柄 m_nThreadID = ::GetCurrentThreadId();//theApp的線程ID等于當(dāng)前線程ID |
所以CWinApp類(lèi)幾乎只是為MFC程序的第一個(gè)線程量身定制的,它不需要也不能被AfxBeginThread或
theApp.CreateThread"再次"啟動(dòng)。這就是CWinApp類(lèi)和theApp全局變量的內(nèi)涵!如果你要再增加一個(gè)UI線程,不要繼承類(lèi)
CWinApp,而應(yīng)繼承類(lèi)CWinThread。而參考第1節(jié),由于我們一般以主線程(在MFC程序里實(shí)際上就是OS啟動(dòng)的第一個(gè)線程)處理所有窗口的
消息,所以我們幾乎沒(méi)有再啟動(dòng)UI線程的需求!
|
|
|
| 日 | 一 | 二 | 三 | 四 | 五 | 六 |
---|
29 | 30 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|
常用鏈接
留言簿(7)
隨筆檔案
文章分類(lèi)
文章檔案
相冊(cè)
收藏夾
c++
搜索
最新評(píng)論

閱讀排行榜
評(píng)論排行榜
|
|