信號(hào)量
信號(hào)量是維護(hù)0到指定最大值之間的同步對(duì)象。信號(hào)量狀態(tài)在其計(jì)數(shù)大于0時(shí)是有信號(hào)的,而其計(jì)數(shù)是0時(shí)是無信號(hào)的。信號(hào)量對(duì)象在控制上可以支持有限數(shù)量共享資源的訪問。
信號(hào)量的特點(diǎn)和用途可用下列幾句話定義:
?。?)如果當(dāng)前資源的數(shù)量大于0,則信號(hào)量有效;
?。?)如果當(dāng)前資源數(shù)量是0,則信號(hào)量無效;
(3)系統(tǒng)決不允許當(dāng)前資源的數(shù)量為負(fù)值;
?。?)當(dāng)前資源數(shù)量決不能大于最大資源數(shù)量。
創(chuàng)建信號(hào)量
HANDLE CreateSemaphore ( PSECURITY_ATTRIBUTE psa, LONG lInitialCount, //開始時(shí)可供使用的資源數(shù) LONG lMaximumCount, //最大資源數(shù) PCTSTR pszName); |
釋放信號(hào)量
通過調(diào)用ReleaseSemaphore函數(shù),線程就能夠?qū)π艠?biāo)的當(dāng)前資源數(shù)量進(jìn)行遞增,該函數(shù)原型為:
BOOL WINAPI ReleaseSemaphore( HANDLE hSemaphore, LONG lReleaseCount, //信號(hào)量的當(dāng)前資源數(shù)增加lReleaseCount LPLONG lpPreviousCount ); |
打開信號(hào)量
和其他核心對(duì)象一樣,信號(hào)量也可以通過名字跨進(jìn)程訪問,打開信號(hào)量的API為:
HANDLE OpenSemaphore ( DWORD fdwAccess, BOOL bInherithandle, PCTSTR pszName ); |
互鎖訪問
當(dāng)必須以原子操作方式來修改單個(gè)值時(shí),互鎖訪問函數(shù)是相當(dāng)有用的。所謂原子訪問,是指線程在訪問資源時(shí)能夠確保所有其他線程都不在同一時(shí)間內(nèi)訪問相同的資源。
請(qǐng)看下列代碼:
int globalVar = 0;
DWORD WINAPI ThreadFunc1(LPVOID n) { globalVar++; return 0; } DWORD WINAPI ThreadFunc2(LPVOID n) { globalVar++; return 0; } |
運(yùn)行ThreadFunc1和ThreadFunc2線程,結(jié)果是不可預(yù)料的,因?yàn)間lobalVar++并不對(duì)應(yīng)著一條機(jī)器指令,我們看看globalVar++的反匯編代碼:
00401038 mov eax,[globalVar (0042d3f0)] 0040103D add eax,1 00401040 mov [globalVar (0042d3f0)],eax |
在"mov eax,[globalVar (0042d3f0)]" 指令與"add eax,1" 指令以及"add eax,1" 指令與"mov [globalVar (0042d3f0)],eax"指令之間都可能發(fā)生線程切換,使得程序的執(zhí)行后globalVar的結(jié)果不能確定。我們可以使用InterlockedExchangeAdd函數(shù)解決這個(gè)問題:
int globalVar = 0;
DWORD WINAPI ThreadFunc1(LPVOID n) { InterlockedExchangeAdd(&globalVar,1); return 0; } DWORD WINAPI ThreadFunc2(LPVOID n) { InterlockedExchangeAdd(&globalVar,1); return 0; } |
InterlockedExchangeAdd保證對(duì)變量globalVar的訪問具有"原子性"。互鎖訪問的控制速度非???,調(diào)用一個(gè)互鎖函數(shù)的CPU周期通常小于50,不需要進(jìn)行用戶方式與內(nèi)核方式的切換(該切換通常需要運(yùn)行1000個(gè)CPU周期)。
互鎖訪問函數(shù)的缺點(diǎn)在于其只能對(duì)單一變量進(jìn)行原子訪問,如果要訪問的資源比較復(fù)雜,仍要使用臨界區(qū)或互斥。
可等待定時(shí)器
可等待定時(shí)器是在某個(gè)時(shí)間或按規(guī)定的間隔時(shí)間發(fā)出自己的信號(hào)通知的內(nèi)核對(duì)象。它們通常用來在某個(gè)時(shí)間執(zhí)行某個(gè)操作。
創(chuàng)建可等待定時(shí)器
HANDLE CreateWaitableTimer( PSECURITY_ATTRISUTES psa, BOOL fManualReset,//人工重置或自動(dòng)重置定時(shí)器 PCTSTR pszName); |
設(shè)置可等待定時(shí)器
可等待定時(shí)器對(duì)象在非激活狀態(tài)下被創(chuàng)建,程序員應(yīng)調(diào)用 SetWaitableTimer函數(shù)來界定定時(shí)器在何時(shí)被激活:
BOOL SetWaitableTimer( HANDLE hTimer, //要設(shè)置的定時(shí)器 const LARGE_INTEGER *pDueTime, //指明定時(shí)器第一次激活的時(shí)間 LONG lPeriod, //指明此后定時(shí)器應(yīng)該間隔多長時(shí)間激活一次 PTIMERAPCROUTINE pfnCompletionRoutine, PVOID PvArgToCompletionRoutine, BOOL fResume); |
取消可等待定時(shí)器
BOOl Cancel WaitableTimer( HANDLE hTimer //要取消的定時(shí)器 ); |
打開可等待定時(shí)器
作為一種內(nèi)核對(duì)象,WaitableTimer也可以被其他進(jìn)程以名字打開:
HANDLE OpenWaitableTimer ( DWORD fdwAccess, BOOL bInherithandle, PCTSTR pszName ); |
實(shí)例
下面給出的一個(gè)程序可能發(fā)生死鎖現(xiàn)象:
#include <windows.h> #include <stdio.h> CRITICAL_SECTION cs1, cs2; long WINAPI ThreadFn(long); main() { long iThreadID; InitializeCriticalSection(&cs1); InitializeCriticalSection(&cs2); CloseHandle(CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadFn, NULL, 0,&iThreadID)); while (TRUE) { EnterCriticalSection(&cs1); printf("\n線程1占用臨界區(qū)1"); EnterCriticalSection(&cs2); printf("\n線程1占用臨界區(qū)2");
printf("\n線程1占用兩個(gè)臨界區(qū)");
LeaveCriticalSection(&cs2); LeaveCriticalSection(&cs1);
printf("\n線程1釋放兩個(gè)臨界區(qū)"); Sleep(20); }; return (0); }
long WINAPI ThreadFn(long lParam) { while (TRUE) { EnterCriticalSection(&cs2); printf("\n線程2占用臨界區(qū)2"); EnterCriticalSection(&cs1); printf("\n線程2占用臨界區(qū)1");
printf("\n線程2占用兩個(gè)臨界區(qū)");
LeaveCriticalSection(&cs1); LeaveCriticalSection(&cs2);
printf("\n線程2釋放兩個(gè)臨界區(qū)"); Sleep(20); }; } |
運(yùn)行這個(gè)程序,在中途一旦發(fā)生這樣的輸出:
線程1占用臨界區(qū)1
線程2占用臨界區(qū)2
或
線程2占用臨界區(qū)2
線程1占用臨界區(qū)1
或
線程1占用臨界區(qū)2
線程2占用臨界區(qū)1
或
線程2占用臨界區(qū)1
線程1占用臨界區(qū)2
程序就"死"掉了,再也運(yùn)行不下去。因?yàn)檫@樣的輸出,意味著兩個(gè)線程相互等待對(duì)方釋放臨界區(qū),也即出現(xiàn)了死鎖。
如果我們將線程2的控制函數(shù)改為:
long WINAPI ThreadFn(long lParam) { while (TRUE) { EnterCriticalSection(&cs1); printf("\n線程2占用臨界區(qū)1"); EnterCriticalSection(&cs2); printf("\n線程2占用臨界區(qū)2");
printf("\n線程2占用兩個(gè)臨界區(qū)");
LeaveCriticalSection(&cs1); LeaveCriticalSection(&cs2);
printf("\n線程2釋放兩個(gè)臨界區(qū)"); Sleep(20); }; } |
再次運(yùn)行程序,死鎖被消除,程序不再擋掉。這是因?yàn)槲覀兏淖兞司€程2中獲得臨界區(qū)1、2的順序,消除了線程1、2相互等待資源的可能性。
由此我們得出結(jié)論,在使用線程間的同步機(jī)制時(shí),要特別留心死鎖的發(fā)生。 深入淺出Win32多線程設(shè)計(jì)之MFC的多線程 1、創(chuàng)建和終止線程 在MFC程序中創(chuàng)建一個(gè)線程,宜調(diào)用AfxBeginThread函數(shù)。該函數(shù)因參數(shù)不同而具有兩種重載版本,分別對(duì)應(yīng)工作者線程和用戶接口(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)單,只需編寫線程控制函數(shù)和啟動(dòng)線程即可。下面的代碼給出了定義一個(gè)控制函數(shù)和啟動(dòng)它的過程: //線程控制函數(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)建用戶界面線程時(shí),必須首先從CWinThread 派生類,并使用 DECLARE_DYNCREATE 和 IMPLEMENT_DYNCREATE 宏聲明此類。 下面給出了CWinThread類的原型(添加了關(guān)于其重要函數(shù)功能和是否需要被繼承類重載的注釋): 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í)例初始化,必須重寫 virtual BOOL InitInstance();
// running and idle processing //控制線程的函數(shù),包含消息泵,一般不重寫 virtual int Run();
//消息調(diào)度到TranslateMessage和DispatchMessage之前對(duì)其進(jìn)行篩選, //通常不重寫 virtual BOOL PreTranslateMessage(MSG* pMsg);
virtual BOOL PumpMessage(); // low level message pump
//執(zhí)行線程特定的閑置時(shí)間處理,通常不重寫 virtual BOOL OnIdle(LONG lCount); // return TRUE if more idle processing virtual BOOL IsIdleMessage(MSG* pMsg); // checks for special messages
//線程終止時(shí)執(zhí)行清除,通常需要重寫 virtual int ExitInstance(); // default will 'delete this'
//截獲由線程的消息和命令處理程序引發(fā)的未處理異常,通常不重寫 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派生的類的 RUNTIME_CLASS CRuntimeClass *pThreadClass, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL ); |
我們可以方便地使用VC++ 6.0類向?qū)Фx一個(gè)繼承自CWinThread的用戶線程類。下面給出產(chǎn)生我們自定義的CWinThread子類CMyUIThread的方法。 打開VC++ 6.0類向?qū)В谌缦麓翱谥羞x擇Base Class類為CWinThread,輸入子類名為CMyUIThread,點(diǎn)擊"OK"按鈕后就產(chǎn)生了類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)建線程,而是分如下兩步完成: ?。?)調(diào)用線程類的構(gòu)造函數(shù)創(chuàng)建一個(gè)線程對(duì)象; ?。?)調(diào)用CWinThread::CreateThread函數(shù)來啟動(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è)線程,他后來澄清了這個(gè)錯(cuò)誤。因?yàn)槿绻麨镸DI程序的每個(gè)窗口都單獨(dú)創(chuàng)建一個(gè)線程,在窗口進(jìn)行切換的時(shí)候,將進(jìn)行線程的上下文切換! 2.線程間通信 MFC中定義了繼承自CSyncObject類的CCriticalSection 、CCEvent、CMutex、CSemaphore類封裝和簡(jiǎn)化了WIN32 API所提供的臨界區(qū)、事件、互斥和信號(hào)量。使用這些同步機(jī)制,必須包含"Afxmt.h"頭文件。下圖給出了類的繼承關(guān)系: 作為CSyncObject類的繼承類,我們僅僅使用基類CSyncObject的接口函數(shù)就可以方便、統(tǒng)一的操作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類最主要的兩個(gè)函數(shù)是Lock和Unlock,若我們直接使用CSyncObject類及其派生類,我們需要非常小心地在Lock之后調(diào)用Unlock。 MFC提供的另兩個(gè)類CSingleLock(等待一個(gè)對(duì)象)和CMultiLock(等待多個(gè)對(duì)象)為我們編寫應(yīng)用程序提供了更靈活的機(jī)制,下面以實(shí)際來闡述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類的對(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)該作為"定理"被記?。?br> "定理" 一 所有產(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ì)列處理的過程將有助于我們進(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: ?。?) 輸入MFC EXE工程名MFCThread; ?。?) 選擇單文檔架構(gòu),不支持Document/View結(jié)構(gòu); ?。?) ActiveX、3D container等其他選項(xiàng)都選擇無。 我們來分析這個(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)的類CMFCThreadApp繼承自CWinApp類,而CWinApp類又繼承自CWinThread類(CWinThread類又繼承自CCmdTarget類),所以CMFCThread本質(zhì)上是一個(gè)MFC線程類,下圖給出了相關(guān)的類層次結(jié)構(gòu): 我們提取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 所完成的工作現(xiàn)在由CWinApp 的三個(gè)函數(shù)完成: virtual BOOL InitApplication(); virtual BOOL InitInstance(); virtual int Run(); |
"CMFCThreadApp theApp;"語句定義的全局變量theApp是整個(gè)程式的application object,每一個(gè)MFC 應(yīng)用程序都有一個(gè)。當(dāng)我們執(zhí)行MFCThread程序的時(shí)候,這個(gè)全局變量被構(gòu)造。theApp 配置完成后,WinMain開始執(zhí)行。但是程序中并沒有WinMain的代碼,它在哪里呢?原來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è)窗口類別的場(chǎng)所;InitInstance是產(chǎn)生窗口并顯示窗口的場(chǎng)所;Run是提取并分派消息的場(chǎng)所。這樣,MFC就同WIN32 SDK程序?qū)?yīng)起來了。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消息的"繞行"過程。 在MFC中,只要是CWnd 衍生類別,就可以攔下任何Windows消息。與窗口無關(guān)的MFC類別(例如CDocument 和CWinApp)如果也想處理消息,必須衍生自CCmdTarget,并且只可能收到WM_COMMAND消息。所有能進(jìn)行MESSAGE_MAP的類都繼承自CCmdTarget,如: MFC中MESSAGE_MAP的定義依賴于以下三個(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è)消息的"繞行"。 看到這里相信你有這樣的疑問:程序定義了CWinApp類的theApp全局變量,可是從來沒有調(diào)用AfxBeginThread或theApp.CreateThread啟動(dòng)線程呀,theApp對(duì)應(yīng)的線程是怎么啟動(dòng)的? 答:MFC在這里用了很高明的一招。實(shí)際上,程序開始運(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類幾乎只是為MFC程序的第一個(gè)線程量身定制的,它不需要也不能被AfxBeginThread或theApp.CreateThread"再次"啟動(dòng)。這就是CWinApp類和theApp全局變量的內(nèi)涵!如果你要再增加一個(gè)UI線程,不要繼承類CWinApp,而應(yīng)繼承類CWinThread。而參考第1節(jié),由于我們一般以主線程(在MFC程序里實(shí)際上就是OS啟動(dòng)的第一個(gè)線程)處理所有窗口的消息,所以我們幾乎沒有再啟動(dòng)UI線程的需求! 深入淺出Win32多線程程序設(shè)計(jì)之綜合實(shí)例 本章我們將以工業(yè)控制和嵌入式系統(tǒng)中運(yùn)用極為廣泛的串口通信為例講述多線程的典型應(yīng)用。
而網(wǎng)絡(luò)通信也是多線程應(yīng)用最廣泛的領(lǐng)域之一,所以本章的最后一節(jié)也將對(duì)多線程網(wǎng)絡(luò)通信進(jìn)行簡(jiǎn)短的描述。
1.串口通信
在工業(yè)控制系統(tǒng)中,工控機(jī)(一般都基于PC Windows平臺(tái))經(jīng)常需要與單片機(jī)通過串口進(jìn)行通信。因此,操作和使用PC的串口成為大多數(shù)單片機(jī)、嵌入式系統(tǒng)領(lǐng)域工程師必須具備的能力。
串口的使用需要通過三個(gè)步驟來完成的:
(1) 打開通信端口;
(2) 初始化串口,設(shè)置波特率、數(shù)據(jù)位、停止位、奇偶校驗(yàn)等參數(shù)。為了給讀者一個(gè)直觀的印象,下圖從Windows的"控制面板->系統(tǒng)->設(shè)備管理器->通信端口(COM1)"打開COM的設(shè)置窗口:
(3) 讀寫串口。
在WIN32平臺(tái)下,對(duì)通信端口進(jìn)行操作跟基本的文件操作一樣。
創(chuàng)建/打開COM資源
下列函數(shù)如果調(diào)用成功,則返回一個(gè)標(biāo)識(shí)通信端口的句柄,否則返回-1:
HADLE CreateFile(PCTSTR lpFileName, //通信端口名,如"COM1" WORD dwDesiredAccess, //對(duì)資源的訪問類型 WORD dwShareMode, //指定共享模式,COM不能共享,該參數(shù)為0 PSECURITY_ATTRIBUTES lpSecurityAttributes, //安全描述符指針,可為NULL WORD dwCreationDisposition, //創(chuàng)建方式 WORD dwFlagsAndAttributes, //文件屬性,可為NULL HANDLE hTemplateFile //模板文件句柄,置為NULL ); |
獲得/設(shè)置COM屬性
下列函數(shù)可以獲得COM口的設(shè)備控制塊,從而獲得相關(guān)參數(shù):
BOOL WINAPI GetCommState( HANDLE hFile, //標(biāo)識(shí)通信端口的句柄 LPDCB lpDCB //指向一個(gè)設(shè)備控制塊(DCB結(jié)構(gòu))的指針 ); |
如果要調(diào)整通信端口的參數(shù),則需要重新配置設(shè)備控制塊,再用WIN32 API SetCommState()函數(shù)進(jìn)行設(shè)置:
BOOL SetCommState( HANDLE hFile, //標(biāo)識(shí)通信端口的句柄 LPDCB lpDCB //指向一個(gè)設(shè)備控制塊(DCB結(jié)構(gòu))的指針 ); |
DCB結(jié)構(gòu)包含了串口的各項(xiàng)參數(shù)設(shè)置,如下:
typedef struct _DCB { // dcb DWORD DCBlength; // sizeof(DCB) DWORD BaudRate; // current baud rate DWORD fBinary: 1; // binary mode, no EOF check DWORD fParity: 1; // enable parity checking DWORD fOutxCtsFlow: 1; // CTS output flow control DWORD fOutxDsrFlow: 1; // DSR output flow control DWORD fDtrControl: 2; // DTR flow control type DWORD fDsrSensitivity: 1; // DSR sensitivity DWORD fTXContinueOnXoff: 1; // XOFF continues Tx DWORD fOutX: 1; // XON/XOFF out flow control DWORD fInX: 1; // XON/XOFF in flow control DWORD fErrorChar: 1; // enable error replacement DWORD fNull: 1; // enable null stripping DWORD fRtsControl: 2; // RTS flow control DWORD fAbortOnError: 1; // abort reads/writes on error DWORD fDummy2: 17; // reserved WORD wReserved; // not currently used WORD XonLim; // transmit XON threshold WORD XoffLim; // transmit XOFF threshold BYTE ByteSize; // number of bits/byte, 4-8 BYTE Parity; // 0-4=no,odd,even,mark,space BYTE StopBits; // 0,1,2 = 1, 1.5, 2 char XonChar; // Tx and Rx XON character char XoffChar; // Tx and Rx XOFF character char ErrorChar; // error replacement character char EofChar; // end of input character char EvtChar; // received event character WORD wReserved1; // reserved; do not use } DCB; |
讀寫串口
在讀寫串口之前,還要用PurgeComm()函數(shù)清空緩沖區(qū),并用SetCommMask ()函數(shù)設(shè)置事件掩模來監(jiān)視指定通信端口上的事件,其原型為:
BOOL SetCommMask( HANDLE hFile, //標(biāo)識(shí)通信端口的句柄 DWORD dwEvtMask //能夠使能的通信事件 ); |
串口上可能發(fā)生的事件如下表所示:
值 | 事件描述 | EV_BREAK | A break was detected on input. | EV_CTS | The CTS (clear-to-send) signal changed state. | EV_DSR | The DSR(data-set-ready) signal changed state. | EV_ERR | A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY. | EV_RING | A ring indicator was detected. | EV_RLSD | The RLSD (receive-line-signal-detect) signal changed state. | EV_RXCHAR | A character was received and placed in the input buffer. | EV_RXFLAG | The event character was received and placed in the input buffer. The event character is specified in the device's DCB structure, which is applied to a serial port by using the SetCommState function. | EV_TXEMPTY | The last character in the output buffer was sent. |
在設(shè)置好事件掩模后,我們就可以利用WaitCommEvent()函數(shù)來等待串口上發(fā)生事件,其函數(shù)原型為:
BOOL WaitCommEvent( HANDLE hFile, //標(biāo)識(shí)通信端口的句柄 LPDWORD lpEvtMask, //指向存放事件標(biāo)識(shí)變量的指針 LPOVERLAPPED lpOverlapped, // 指向overlapped結(jié)構(gòu) ); |
我們可以在發(fā)生事件后,根據(jù)相應(yīng)的事件類型,進(jìn)行串口的讀寫操作:
BOOL ReadFile(HANDLE hFile, //標(biāo)識(shí)通信端口的句柄 LPVOID lpBuffer, //輸入數(shù)據(jù)Buffer指針 DWORD nNumberOfBytesToRead, // 需要讀取的字節(jié)數(shù) LPDWORD lpNumberOfBytesRead, //實(shí)際讀取的字節(jié)數(shù)指針 LPOVERLAPPED lpOverlapped //指向overlapped結(jié)構(gòu) ); BOOL WriteFile(HANDLE hFile, //標(biāo)識(shí)通信端口的句柄 LPCVOID lpBuffer, //輸出數(shù)據(jù)Buffer指針 DWORD nNumberOfBytesToWrite, //需要寫的字節(jié)數(shù) LPDWORD lpNumberOfBytesWritten, //實(shí)際寫入的字節(jié)數(shù)指針 LPOVERLAPPED lpOverlapped //指向overlapped結(jié)構(gòu) ); | 2.工程實(shí)例
下面我們用第1節(jié)所述API實(shí)現(xiàn)一個(gè)多線程的串口通信程序。這個(gè)例子工程(工程名為MultiThreadCom)的界面很簡(jiǎn)單,如下圖所示:
它是一個(gè)多線程的應(yīng)用程序,包括兩個(gè)工作者線程,分別處理串口1和串口2。為了簡(jiǎn)化問題,我們讓連接兩個(gè)串口的電纜只包含RX、TX兩根連線(即不以硬件控制RS-232,串口上只會(huì)發(fā)生EV_TXEMPTY、EV_RXCHAR事件)。
在工程實(shí)例的BOOL CMultiThreadComApp::InitInstance()函數(shù)中,啟動(dòng)并設(shè)置COM1和COM2,其源代碼為:
BOOL CMultiThreadComApp::InitInstance() { AfxEnableControlContainer(); //打開并設(shè)置COM1 hComm1=CreateFile("COM1", GENERIC_READ|GENERIC_WRITE, 0, NULL ,OPEN_EXISTING, 0,NULL); if (hComm1==(HANDLE)-1) { AfxMessageBox("打開COM1失敗"); return false; } else { DCB wdcb; GetCommState (hComm1,&wdcb); wdcb.BaudRate=9600; SetCommState (hComm1,&wdcb); PurgeComm(hComm1,PURGE_TXCLEAR); } //打開并設(shè)置COM2 hComm2=CreateFile("COM2", GENERIC_READ|GENERIC_WRITE, 0, NULL ,OPEN_EXISTING, 0,NULL); if (hComm2==(HANDLE)-1) { AfxMessageBox("打開COM2失敗"); return false; } else { DCB wdcb; GetCommState (hComm2,&wdcb); wdcb.BaudRate=9600; SetCommState (hComm2,&wdcb); PurgeComm(hComm2,PURGE_TXCLEAR); }
CMultiThreadComDlg dlg; m_pMainWnd = &dlg; int nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } return FALSE; } |
此后我們?cè)趯?duì)話框CMultiThreadComDlg的初始化函數(shù)OnInitDialog中啟動(dòng)兩個(gè)分別處理COM1和COM2的線程:
BOOL CMultiThreadComDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } }
// Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here //啟動(dòng)串口1處理線程 DWORD nThreadId1; hCommThread1 = ::CreateThread((LPSECURITY_ATTRIBUTES)NULL, 0, (LPTHREAD_START_ROUTINE)Com1ThreadProcess, AfxGetMainWnd()->m_hWnd, 0, &nThreadId1); if (hCommThread1 == NULL) { AfxMessageBox("創(chuàng)建串口1處理線程失敗"); return false; } //啟動(dòng)串口2處理線程 DWORD nThreadId2; hCommThread2 = ::CreateThread((LPSECURITY_ATTRIBUTES)NULL, 0, (LPTHREAD_START_ROUTINE)Com2ThreadProcess, AfxGetMainWnd()->m_hWnd, 0, &nThreadId2); if (hCommThread2 == NULL) { AfxMessageBox("創(chuàng)建串口2處理線程失敗"); return false; }
return TRUE; // return TRUE unless you set the focus to a control } |
兩個(gè)串口COM1和COM2對(duì)應(yīng)的線程處理函數(shù)等待串口上發(fā)生事件,并根據(jù)事件類型和自身緩沖區(qū)是否有數(shù)據(jù)要發(fā)送進(jìn)行相應(yīng)的處理,其源代碼為:
DWORD WINAPI Com1ThreadProcess(HWND hWnd//主窗口句柄) { DWORD wEven; char str[10]; //讀入數(shù)據(jù) SetCommMask(hComm1, EV_RXCHAR | EV_TXEMPTY); while (TRUE) { WaitCommEvent(hComm1, &wEven, NULL); if(wEven = 0) { CloseHandle(hCommThread1); hCommThread1 = NULL; ExitThread(0); } else { switch (wEven) { case EV_TXEMPTY: if (wTxPos < wTxLen) { //在串口1寫入數(shù)據(jù) DWORD wCount; //寫入的字節(jié)數(shù) WriteFile(hComm1, com1Data.TxBuf[wTxPos], 1, &wCount, NULL); com1Data.wTxPos++; } break; case EV_RXCHAR: if (com1Data.wRxPos < com1Data.wRxLen) { //讀取串口數(shù)據(jù), 處理收到的數(shù)據(jù) DWORD wCount; //讀取的字節(jié)數(shù) ReadFile(hComm1, com1Data.RxBuf[wRxPos], 1, &wCount, NULL); com1Data.wRxPos++; if(com1Data.wRxPos== com1Data.wRxLen); ::PostMessage(hWnd, COM_SENDCHAR, 0, 1); } break; } } } } return TRUE; }
DWORD WINAPI Com2ThreadProcess(HWND hWnd //主窗口句柄) { DWORD wEven; char str[10]; //讀入數(shù)據(jù) SetCommMask(hComm2, EV_RXCHAR | EV_TXEMPTY); while (TRUE) { WaitCommEvent(hComm2, &wEven, NULL); if (wEven = 0) { CloseHandle(hCommThread2); hCommThread2 = NULL; ExitThread(0); } else { switch (wEven) { case EV_TXEMPTY: if (wTxPos < wTxLen) { //在串口2寫入數(shù)據(jù) DWORD wCount; //寫入的字節(jié)數(shù) WriteFile(hComm2, com2Data.TxBuf[wTxPos], 1, &wCount, NULL); com2Data.wTxPos++; } break; case EV_RXCHAR: if (com2Data.wRxPos < com2Data.wRxLen) { //讀取串口數(shù)據(jù), 處理收到的數(shù)據(jù) DWORD wCount; //讀取的字節(jié)數(shù) ReadFile(hComm2, com2Data.RxBuf[wRxPos], 1, &wCount, NULL); com2Data.wRxPos++; if(com2Data.wRxPos== com2Data.wRxLen); ::PostMessage(hWnd, COM_SENDCHAR, 0, 1); } break; } } } return TRUE; } |
線程控制函數(shù)中所操作的com1Data和com2Data是與串口對(duì)應(yīng)的數(shù)據(jù)結(jié)構(gòu)struct tagSerialPort的實(shí)例,這個(gè)數(shù)據(jù)結(jié)構(gòu)是:
typedef struct tagSerialPort { BYTE RxBuf[SPRX_BUFLEN];//接收Buffer WORD wRxPos; //當(dāng)前接收字節(jié)位置 WORD wRxLen; //要接收的字節(jié)數(shù) BYTE TxBuf[SPTX_BUFLEN];//發(fā)送Buffer WORD wTxPos; //當(dāng)前發(fā)送字節(jié)位置 WORD wTxLen; //要發(fā)送的字節(jié)數(shù) }SerialPort, * LPSerialPort; | 3.多線程串口類
使用多線程串口通信更方便的途徑是編寫一個(gè)多線程的串口類,例如Remon Spekreijse編寫了一個(gè)CSerialPort串口類。仔細(xì)分析這個(gè)類的源代碼,將十分有助于我們對(duì)先前所學(xué)多線程及同步知識(shí)的理解。
3.1類的定義
#ifndef __SERIALPORT_H__ #define __SERIALPORT_H__
#define WM_COMM_BREAK_DETECTED WM_USER+1 // A break was detected on input. #define WM_COMM_CTS_DETECTED WM_USER+2 // The CTS (clear-to-send) signal changed state. #define WM_COMM_DSR_DETECTED WM_USER+3 // The DSR (data-set-ready) signal changed state. #define WM_COMM_ERR_DETECTED WM_USER+4 // A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY. #define WM_COMM_RING_DETECTED WM_USER+5 // A ring indicator was detected. #define WM_COMM_RLSD_DETECTED WM_USER+6 // The RLSD (receive-line-signal-detect) signal changed state. #define WM_COMM_RXCHAR WM_USER+7 // A character was received and placed in the input buffer. #define WM_COMM_RXFLAG_DETECTED WM_USER+8 // The event character was received and placed in the input buffer. #define WM_COMM_TXEMPTY_DETECTED WM_USER+9 // The last character in the output buffer was sent.
class CSerialPort { public: // contruction and destruction CSerialPort(); virtual ~CSerialPort();
// port initialisation BOOL InitPort(CWnd* pPortOwner, UINT portnr = 1, UINT baud = 19200, char parity = 'N', UINT databits = 8, UINT stopsbits = 1, DWORD dwCommEvents = EV_RXCHAR | EV_CTS, UINT nBufferSize = 512);
// start/stop comm watching BOOL StartMonitoring(); BOOL RestartMonitoring(); BOOL StopMonitoring();
DWORD GetWriteBufferSize(); DWORD GetCommEvents(); DCB GetDCB();
void WriteToPort(char* string);
protected: // protected memberfunctions void ProcessErrorMessage(char* ErrorText); static UINT CommThread(LPVOID pParam); static void ReceiveChar(CSerialPort* port, COMSTAT comstat); static void WriteChar(CSerialPort* port);
// thread CWinThread* m_Thread;
// synchronisation objects CRITICAL_SECTION m_csCommunicationSync; BOOL m_bThreadAlive;
// handles HANDLE m_hShutdownEvent; HANDLE m_hComm; HANDLE m_hWriteEvent;
// Event array. // One element is used for each event. There are two event handles for each port. // A Write event and a receive character event which is located in the overlapped structure (m_ov.hEvent). // There is a general shutdown when the port is closed. HANDLE m_hEventArray[3];
// structures OVERLAPPED m_ov; COMMTIMEOUTS m_CommTimeouts; DCB m_dcb;
// owner window CWnd* m_pOwner;
// misc UINT m_nPortNr; char* m_szWriteBuffer; DWORD m_dwCommEvents; DWORD m_nWriteBufferSize; };
#endif __SERIALPORT_H__ |
3.2類的實(shí)現(xiàn)
3.2.1構(gòu)造函數(shù)與析構(gòu)函數(shù)
進(jìn)行相關(guān)變量的賦初值及內(nèi)存恢復(fù):
CSerialPort::CSerialPort() { m_hComm = NULL;
// initialize overlapped structure members to zero m_ov.Offset = 0; m_ov.OffsetHigh = 0;
// create events m_ov.hEvent = NULL; m_hWriteEvent = NULL; m_hShutdownEvent = NULL;
m_szWriteBuffer = NULL;
m_bThreadAlive = FALSE; }
// // Delete dynamic memory // CSerialPort::~CSerialPort() { do { SetEvent(m_hShutdownEvent); } while (m_bThreadAlive);
TRACE("Thread ended\n");
delete []m_szWriteBuffer; } |
3.2.2核心函數(shù):初始化串口
在初始化串口函數(shù)中,將打開串口,設(shè)置相關(guān)參數(shù),并創(chuàng)建串口相關(guān)的用戶控制事件,初始化臨界區(qū)(Critical Section),以成隊(duì)的EnterCriticalSection()、LeaveCriticalSection()函數(shù)進(jìn)行資源的排它性訪問:
BOOL CSerialPort::InitPort(CWnd *pPortOwner, // the owner (CWnd) of the port (receives message) UINT portnr, // portnumber (1..4) UINT baud, // baudrate char parity, // parity UINT databits, // databits UINT stopbits, // stopbits DWORD dwCommEvents, // EV_RXCHAR, EV_CTS etc UINT writebuffersize) // size to the writebuffer { assert(portnr > 0 && portnr < 5); assert(pPortOwner != NULL);
// if the thread is alive: Kill if (m_bThreadAlive) { do { SetEvent(m_hShutdownEvent); } while (m_bThreadAlive); TRACE("Thread ended\n"); }
// create events if (m_ov.hEvent != NULL) ResetEvent(m_ov.hEvent); m_ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (m_hWriteEvent != NULL) ResetEvent(m_hWriteEvent); m_hWriteEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (m_hShutdownEvent != NULL) ResetEvent(m_hShutdownEvent); m_hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
// initialize the event objects m_hEventArray[0] = m_hShutdownEvent; // highest priority m_hEventArray[1] = m_ov.hEvent; m_hEventArray[2] = m_hWriteEvent;
// initialize critical section InitializeCriticalSection(&m_csCommunicationSync);
// set buffersize for writing and save the owner m_pOwner = pPortOwner;
if (m_szWriteBuffer != NULL) delete []m_szWriteBuffer; m_szWriteBuffer = new char[writebuffersize];
m_nPortNr = portnr;
m_nWriteBufferSize = writebuffersize; m_dwCommEvents = dwCommEvents;
BOOL bResult = FALSE; char *szPort = new char[50]; char *szBaud = new char[50];
// now it critical! EnterCriticalSection(&m_csCommunicationSync);
// if the port is already opened: close it if (m_hComm != NULL) { CloseHandle(m_hComm); m_hComm = NULL; }
// prepare port strings sprintf(szPort, "COM%d", portnr); sprintf(szBaud, "baud=%d parity=%c data=%d stop=%d", baud, parity, databits,stopbits);
// get a handle to the port m_hComm = CreateFile(szPort, // communication port string (COMX) GENERIC_READ | GENERIC_WRITE, // read/write types 0, // comm devices must be opened with exclusive access NULL, // no security attributes OPEN_EXISTING, // comm devices must use OPEN_EXISTING FILE_FLAG_OVERLAPPED, // Async I/O 0); // template must be 0 for comm devices
if (m_hComm == INVALID_HANDLE_VALUE) { // port not found delete []szPort; delete []szBaud; return FALSE; }
// set the timeout values m_CommTimeouts.ReadIntervalTimeout = 1000; m_CommTimeouts.ReadTotalTimeoutMultiplier = 1000; m_CommTimeouts.ReadTotalTimeoutConstant = 1000; m_CommTimeouts.WriteTotalTimeoutMultiplier = 1000; m_CommTimeouts.WriteTotalTimeoutConstant = 1000;
// configure if (SetCommTimeouts(m_hComm, &m_CommTimeouts)) { if (SetCommMask(m_hComm, dwCommEvents)) { if (GetCommState(m_hComm, &m_dcb)) { m_dcb.fRtsControl = RTS_CONTROL_ENABLE; // set RTS bit high! if (BuildCommDCB(szBaud, &m_dcb)) { if (SetCommState(m_hComm, &m_dcb)) ; // normal operation... continue else ProcessErrorMessage("SetCommState()"); } else ProcessErrorMessage("BuildCommDCB()"); } else ProcessErrorMessage("GetCommState()"); } else ProcessErrorMessage("SetCommMask()"); } else ProcessErrorMessage("SetCommTimeouts()");
delete []szPort; delete []szBaud;
// flush the port PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
// release critical section LeaveCriticalSection(&m_csCommunicationSync);
TRACE("Initialisation for communicationport %d completed.\nUse Startmonitor to communicate.\n", portnr);
return TRUE; } | 3.3.3核心函數(shù):串口線程控制函數(shù)
串口線程處理函數(shù)是整個(gè)類中最核心的部分,它主要完成兩類工作:
(1)利用WaitCommEvent函數(shù)對(duì)串口上發(fā)生的事件進(jìn)行獲取并根據(jù)事件的不同類型進(jìn)行相應(yīng)的處理;
?。?)利用WaitForMultipleObjects函數(shù)對(duì)串口相關(guān)的用戶控制事件進(jìn)行等待并做相應(yīng)處理。
UINT CSerialPort::CommThread(LPVOID pParam) { // Cast the void pointer passed to the thread back to // a pointer of CSerialPort class CSerialPort *port = (CSerialPort*)pParam;
// Set the status variable in the dialog class to // TRUE to indicate the thread is running. port->m_bThreadAlive = TRUE;
// Misc. variables DWORD BytesTransfered = 0; DWORD Event = 0; DWORD CommEvent = 0; DWORD dwError = 0; COMSTAT comstat; BOOL bResult = TRUE;
// Clear comm buffers at startup if (port->m_hComm) // check if the port is opened PurgeComm(port->m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
// begin forever loop. This loop will run as long as the thread is alive. for (;;) { // Make a call to WaitCommEvent(). This call will return immediatly // because our port was created as an async port (FILE_FLAG_OVERLAPPED // and an m_OverlappedStructerlapped structure specified). This call will cause the // m_OverlappedStructerlapped element m_OverlappedStruct.hEvent, which is part of the m_hEventArray to // be placed in a non-signeled state if there are no bytes available to be read, // or to a signeled state if there are bytes available. If this event handle // is set to the non-signeled state, it will be set to signeled when a // character arrives at the port.
// we do this for each port!
bResult = WaitCommEvent(port->m_hComm, &Event, &port->m_ov);
if (!bResult) { // If WaitCommEvent() returns FALSE, process the last error to determin // the reason.. switch (dwError = GetLastError()) { case ERROR_IO_PENDING: { // This is a normal return value if there are no bytes // to read at the port. // Do nothing and continue break; } case 87: { // Under Windows NT, this value is returned for some reason. // I have not investigated why, but it is also a valid reply // Also do nothing and continue. break; } default: { // All other error codes indicate a serious error has // occured. Process this error. port->ProcessErrorMessage("WaitCommEvent()"); break; } } } else { // If WaitCommEvent() returns TRUE, check to be sure there are // actually bytes in the buffer to read. // // If you are reading more than one byte at a time from the buffer // (which this program does not do) you will have the situation occur // where the first byte to arrive will cause the WaitForMultipleObjects() // function to stop waiting. The WaitForMultipleObjects() function // resets the event handle in m_OverlappedStruct.hEvent to the non-signelead state // as it returns. // // If in the time between the reset of this event and the call to // ReadFile() more bytes arrive, the m_OverlappedStruct.hEvent handle will be set again // to the signeled state. When the call to ReadFile() occurs, it will // read all of the bytes from the buffer, and the program will // loop back around to WaitCommEvent(). // // At this point you will be in the situation where m_OverlappedStruct.hEvent is set, // but there are no bytes available to read. If you proceed and call // ReadFile(), it will return immediatly due to the async port setup, but // GetOverlappedResults() will not return until the next character arrives. // // It is not desirable for the GetOverlappedResults() function to be in // this state. The thread shutdown event (event 0) and the WriteFile() // event (Event2) will not work if the thread is blocked by GetOverlappedResults(). // // The solution to this is to check the buffer with a call to ClearCommError(). // This call will reset the event handle, and if there are no bytes to read // we can loop back through WaitCommEvent() again, then proceed. // If there are really bytes to read, do nothing and proceed.
bResult = ClearCommError(port->m_hComm, &dwError, &comstat);
if (comstat.cbInQue == 0) continue; } // end if bResult
// Main wait function. This function will normally block the thread // until one of nine events occur that require action. Event = WaitForMultipleObjects(3, port->m_hEventArray, FALSE, INFINITE);
switch (Event) { case 0: { // Shutdown event. This is event zero so it will be // the higest priority and be serviced first.
port->m_bThreadAlive = FALSE;
// Kill this thread. break is not needed, but makes me feel better. AfxEndThread(100); break; } case 1: // read event { GetCommMask(port->m_hComm, &CommEvent); if (CommEvent &EV_CTS) ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_CTS_DETECTED, (WPARAM)0, (LPARAM)port->m_nPortNr); if (CommEvent &EV_RXFLAG) ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_RXFLAG_DETECTED,(WPARAM)0, (LPARAM)port->m_nPortNr); if (CommEvent &EV_BREAK) ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_BREAK_DETECTED,(WPARAM)0, (LPARAM)port->m_nPortNr); if (CommEvent &EV_ERR) ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_ERR_DETECTED, (WPARAM)0, (LPARAM)port->m_nPortNr); if (CommEvent &EV_RING) ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_RING_DETECTED,(WPARAM)0, (LPARAM)port->m_nPortNr); if (CommEvent &EV_RXCHAR) // Receive character event from port. ReceiveChar(port, comstat); break; } case 2: // write event { // Write character event from port WriteChar(port); break; } } // end switch } // close forever loop return 0; } |
下列三個(gè)函數(shù)用于對(duì)串口線程進(jìn)行啟動(dòng)、掛起和恢復(fù):
// // start comm watching // BOOL CSerialPort::StartMonitoring() { if (!(m_Thread = AfxBeginThread(CommThread, this))) return FALSE; TRACE("Thread started\n"); return TRUE; }
// // Restart the comm thread // BOOL CSerialPort::RestartMonitoring() { TRACE("Thread resumed\n"); m_Thread->ResumeThread(); return TRUE; }
// // Suspend the comm thread // BOOL CSerialPort::StopMonitoring() { TRACE("Thread suspended\n"); m_Thread->SuspendThread(); return TRUE; } |
3.3.4讀寫串口
下面一組函數(shù)是用戶對(duì)串口進(jìn)行讀寫操作的接口:
// // Write a character. // void CSerialPort::WriteChar(CSerialPort *port) { BOOL bWrite = TRUE; BOOL bResult = TRUE;
DWORD BytesSent = 0;
ResetEvent(port->m_hWriteEvent);
// Gain ownership of the critical section EnterCriticalSection(&port->m_csCommunicationSync);
if (bWrite) { // Initailize variables port->m_ov.Offset = 0; port->m_ov.OffsetHigh = 0;
// Clear buffer PurgeComm(port->m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
bResult = WriteFile(port->m_hComm, // Handle to COMM Port port->m_szWriteBuffer, // Pointer to message buffer in calling finction strlen((char*)port->m_szWriteBuffer), // Length of message to send &BytesSent, // Where to store the number of bytes sent &port->m_ov); // Overlapped structure
// deal with any error codes if (!bResult) { DWORD dwError = GetLastError(); switch (dwError) { case ERROR_IO_PENDING: { // continue to GetOverlappedResults() BytesSent = 0; bWrite = FALSE; break; } default: { // all other error codes port->ProcessErrorMessage("WriteFile()"); } } } else { LeaveCriticalSection(&port->m_csCommunicationSync); } } // end if(bWrite)
if (!bWrite) { bWrite = TRUE;
bResult = GetOverlappedResult(port->m_hComm, // Handle to COMM port &port->m_ov, // Overlapped structure &BytesSent, // Stores number of bytes sent TRUE); // Wait flag
LeaveCriticalSection(&port->m_csCommunicationSync);
// deal with the error code if (!bResult) { port->ProcessErrorMessage("GetOverlappedResults() in WriteFile()"); } } // end if (!bWrite)
// Verify that the data size send equals what we tried to send if (BytesSent != strlen((char*)port->m_szWriteBuffer)) { TRACE("WARNING: WriteFile() error.. Bytes Sent: %d; Message Length: %d\n", BytesSent, strlen((char*)port->m_szWriteBuffer)); } }
// // Character received. Inform the owner // void CSerialPort::ReceiveChar(CSerialPort *port, COMSTAT comstat) { BOOL bRead = TRUE; BOOL bResult = TRUE; DWORD dwError = 0; DWORD BytesRead = 0; unsigned char RXBuff;
for (;;) { // Gain ownership of the comm port critical section. // This process guarantees no other part of this program // is using the port object.
EnterCriticalSection(&port->m_csCommunicationSync);
// ClearCommError() will update the COMSTAT structure and // clear any other errors.
bResult = ClearCommError(port->m_hComm, &dwError, &comstat);
LeaveCriticalSection(&port->m_csCommunicationSync);
// start forever loop. I use this type of loop because I // do not know at runtime how many loops this will have to // run. My solution is to start a forever loop and to // break out of it when I have processed all of the // data available. Be careful with this approach and // be sure your loop will exit. // My reasons for this are not as clear in this sample // as it is in my production code, but I have found this // solutiion to be the most efficient way to do this.
if (comstat.cbInQue == 0) { // break out when all bytes have been read break; }
EnterCriticalSection(&port->m_csCommunicationSync);
if (bRead) { bResult = ReadFile(port->m_hComm, // Handle to COMM port &RXBuff, // RX Buffer Pointer 1, // Read one byte &BytesRead, // Stores number of bytes read &port->m_ov); // pointer to the m_ov structure // deal with the error code if (!bResult) { switch (dwError = GetLastError()) { case ERROR_IO_PENDING: { // asynchronous i/o is still in progress // Proceed on to GetOverlappedResults(); bRead = FALSE; break; } default: { // Another error has occured. Process this error. port->ProcessErrorMessage("ReadFile()"); break; } } } else { // ReadFile() returned complete. It is not necessary to call GetOverlappedResults() bRead = TRUE; } } // close if (bRead)
if (!bRead) { bRead = TRUE; bResult = GetOverlappedResult(port->m_hComm, // Handle to COMM port &port->m_ov, // Overlapped structure &BytesRead, // Stores number of bytes read TRUE); // Wait flag
// deal with the error code if (!bResult) { port->ProcessErrorMessage("GetOverlappedResults() in ReadFile()"); } } // close if (!bRead)
LeaveCriticalSection(&port->m_csCommunicationSync);
// notify parent that a byte was received ::SendMessage((port->m_pOwner)->m_hWnd, WM_COMM_RXCHAR, (WPARAM)RXBuff,(LPARAM)port->m_nPortNr); } // end forever loop
}
// // Write a string to the port // void CSerialPort::WriteToPort(char *string) { assert(m_hComm != 0);
memset(m_szWriteBuffer, 0, sizeof(m_szWriteBuffer)); strcpy(m_szWriteBuffer, string);
// set event for write SetEvent(m_hWriteEvent); }
// // Return the output buffer size // DWORD CSerialPort::GetWriteBufferSize() { return m_nWriteBufferSize; } | 3.3.5控制接口
應(yīng)用程序員使用下列一組public函數(shù)可以獲取串口的DCB及串口上發(fā)生的事件:
// // Return the device control block // DCB CSerialPort::GetDCB() { return m_dcb; }
// // Return the communication event masks // DWORD CSerialPort::GetCommEvents() { return m_dwCommEvents; } |
3.3.6錯(cuò)誤處理
// // If there is a error, give the right message // void CSerialPort::ProcessErrorMessage(char *ErrorText) { char *Temp = new char[200];
LPVOID lpMsgBuf;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL);
sprintf(Temp, "WARNING: %s Failed with the following error: \n%s\nPort: %d\n", (char*) ErrorText, lpMsgBuf, m_nPortNr); MessageBox(NULL, Temp, "Application Error", MB_ICONSTOP);
LocalFree(lpMsgBuf); delete []Temp; } |
仔細(xì)分析Remon Spekreijse的CSerialPort類對(duì)我們理解多線程及其同步機(jī)制是大有益處的,從http://codeguru.earthweb.com/network/serialport.shtml我們可以獲取CSerialPort類的介紹與工程實(shí)例。另外,電子工業(yè)出版社《Visual C++/Turbo C串口通信編程實(shí)踐》一書的作者龔建偉也編寫了一個(gè)使用CSerialPort類的例子,可以從http://www.gjwtech.com/scomm/sc2serialportclass.htm獲得詳情。
4.多線程網(wǎng)絡(luò)通信
在網(wǎng)絡(luò)通信中使用多線程主要有兩種途徑,即主監(jiān)控線程和線程池。
4.1主監(jiān)控線程
這種方式指的是程序中使用一個(gè)主線程監(jiān)控某特定端口,一旦在這個(gè)端口上發(fā)生連接請(qǐng)求,則主監(jiān)控線程動(dòng)態(tài)使用CreateThread派生出新的子線程處理該請(qǐng)求。主線程在派生子線程后不再對(duì)子線程加以控制和調(diào)度,而由子線程獨(dú)自和客戶方發(fā)生連接并處理異常。
使用這種方法的優(yōu)點(diǎn)是:
?。?)可以較快地實(shí)現(xiàn)原型設(shè)計(jì),尤其在用戶數(shù)目較少、連接保持時(shí)間較長時(shí)有表現(xiàn)較好;
?。?)主線程不與子線程發(fā)生通信,在一定程度上減少了系統(tǒng)資源的消耗。
其缺點(diǎn)是:
?。?)生成和終止子線程的開銷比較大;
?。?)對(duì)遠(yuǎn)端用戶的控制較弱。
這種多線程方式總的特點(diǎn)是"動(dòng)態(tài)生成,靜態(tài)調(diào)度"。
4.2線程池
這種方式指的是主線程在初始化時(shí)靜態(tài)地生成一定數(shù)量的懸掛子線程,放置于線程池中。隨后,主線程將對(duì)這些懸掛子線程進(jìn)行動(dòng)態(tài)調(diào)度。一旦客戶發(fā)出連接請(qǐng)求,主線程將從線程池中查找一個(gè)懸掛的子線程:
?。?)如果找到,主線程將該連接分配給這個(gè)被發(fā)現(xiàn)的子線程。子線程從主線程處接管該連接,并與用戶通信。當(dāng)連接結(jié)束時(shí),該子線程將自動(dòng)懸掛,并進(jìn)人線程池等待再次被調(diào)度;
?。?)如果當(dāng)前已沒有可用的子線程,主線程將通告發(fā)起連接的客戶。
使用這種方法進(jìn)行設(shè)計(jì)的優(yōu)點(diǎn)是:
?。?)主線程可以更好地對(duì)派生的子線程進(jìn)行控制和調(diào)度;
?。?)對(duì)遠(yuǎn)程用戶的監(jiān)控和管理能力較強(qiáng)。
雖然主線程對(duì)子線程的調(diào)度要消耗一定的資源,但是與主監(jiān)控線程方式中派生和終止線程所要耗費(fèi)的資源相比,要少很多。因此,使用該種方法設(shè)計(jì)和實(shí)現(xiàn)的系統(tǒng)在客戶端連接和終止變更頻繁時(shí)有上佳表現(xiàn)。
這種多線程方式總的特點(diǎn)是"靜態(tài)生成,動(dòng)態(tài)調(diào)度"。
|
|