信號量
信號量是維護0到指定最大值之間的同步對象。信號量狀態(tài)在其計數大于0時(shí)是有信號的,而其計數是0時(shí)是無(wú)信號的。信號量對象在控制上可以支持有限數量共享資源的訪(fǎng)問(wèn)。
信號量的特點(diǎn)和用途可用下列幾句話(huà)定義:
?。?)如果當前資源的數量大于0,則信號量有效;
?。?)如果當前資源數量是0,則信號量無(wú)效;
?。?)系統決不允許當前資源的數量為負值;
?。?)當前資源數量決不能大于最大資源數量。
創(chuàng )建信號量
HANDLE CreateSemaphore ( PSECURITY_ATTRIBUTE psa, LONG lInitialCount, //開(kāi)始時(shí)可供使用的資源數 LONG lMaximumCount, //最大資源數 PCTSTR pszName); |
釋放信號量
通過(guò)調用ReleaseSemaphore函數,線(xiàn)程就能夠對信標的當前資源數量進(jìn)行遞增,該函數原型為:
BOOL WINAPI ReleaseSemaphore( HANDLE hSemaphore, LONG lReleaseCount, //信號量的當前資源數增加lReleaseCount LPLONG lpPreviousCount ); |
打開(kāi)信號量
和其他核心對象一樣,信號量也可以通過(guò)名字跨進(jìn)程訪(fǎng)問(wèn),打開(kāi)信號量的API為:
HANDLE OpenSemaphore ( DWORD fdwAccess, BOOL bInherithandle, PCTSTR pszName ); |
互鎖訪(fǎng)問(wèn)
當必須以原子操作方式來(lái)修改單個(gè)值時(shí),互鎖訪(fǎng)問(wèn)函數是相當有用的。所謂原子訪(fǎng)問(wèn),是指線(xiàn)程在訪(fǎng)問(wèn)資源時(shí)能夠確保所有其他線(xiàn)程都不在同一時(shí)間內訪(fǎng)問(wèn)相同的資源。
請看下列代碼:
int globalVar = 0;
DWORD WINAPI ThreadFunc1(LPVOID n) { globalVar++; return 0; } DWORD WINAPI ThreadFunc2(LPVOID n) { globalVar++; return 0; } |
運行ThreadFunc1和ThreadFunc2線(xiàn)程,結果是不可預料的,因為globalVar++并不對應著(zhù)一條機器指令,我們看看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ā)生線(xiàn)程切換,使得程序的執行后globalVar的結果不能確定。我們可以使用InterlockedExchangeAdd函數解決這個(gè)問(wèn)題:
int globalVar = 0;
DWORD WINAPI ThreadFunc1(LPVOID n) { InterlockedExchangeAdd(&globalVar,1); return 0; } DWORD WINAPI ThreadFunc2(LPVOID n) { InterlockedExchangeAdd(&globalVar,1); return 0; } |
InterlockedExchangeAdd保證對變量globalVar的訪(fǎng)問(wèn)具有"原子性"?;ユi訪(fǎng)問(wèn)的控制速度非???,調用一個(gè)互鎖函數的CPU周期通常小于50,不需要進(jìn)行用戶(hù)方式與內核方式的切換(該切換通常需要運行1000個(gè)CPU周期)。
互鎖訪(fǎng)問(wèn)函數的缺點(diǎn)在于其只能對單一變量進(jìn)行原子訪(fǎng)問(wèn),如果要訪(fǎng)問(wèn)的資源比較復雜,仍要使用臨界區或互斥。
可等待定時(shí)器
可等待定時(shí)器是在某個(gè)時(shí)間或按規定的間隔時(shí)間發(fā)出自己的信號通知的內核對象。它們通常用來(lái)在某個(gè)時(shí)間執行某個(gè)操作。
創(chuàng )建可等待定時(shí)器
HANDLE CreateWaitableTimer( PSECURITY_ATTRISUTES psa, BOOL fManualReset,//人工重置或自動(dòng)重置定時(shí)器 PCTSTR pszName); |
設置可等待定時(shí)器
可等待定時(shí)器對象在非激活狀態(tài)下被創(chuàng )建,程序員應調用 SetWaitableTimer函數來(lái)界定定時(shí)器在何時(shí)被激活:
BOOL SetWaitableTimer( HANDLE hTimer, //要設置的定時(shí)器 const LARGE_INTEGER *pDueTime, //指明定時(shí)器第一次激活的時(shí)間 LONG lPeriod, //指明此后定時(shí)器應該間隔多長(cháng)時(shí)間激活一次 PTIMERAPCROUTINE pfnCompletionRoutine, PVOID PvArgToCompletionRoutine, BOOL fResume); |
取消可等待定時(shí)器
BOOl Cancel WaitableTimer( HANDLE hTimer //要取消的定時(shí)器 ); |
打開(kāi)可等待定時(shí)器
作為一種內核對象,WaitableTimer也可以被其他進(jìn)程以名字打開(kāi):
HANDLE OpenWaitableTimer ( DWORD fdwAccess, BOOL bInherithandle, PCTSTR pszName ); |
實(shí)例
下面給出的一個(gè)程序可能發(fā)生死鎖現象:
#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線(xiàn)程1占用臨界區1"); EnterCriticalSection(&cs2); printf("\n線(xiàn)程1占用臨界區2");
printf("\n線(xiàn)程1占用兩個(gè)臨界區");
LeaveCriticalSection(&cs2); LeaveCriticalSection(&cs1);
printf("\n線(xiàn)程1釋放兩個(gè)臨界區"); Sleep(20); }; return (0); }
long WINAPI ThreadFn(long lParam) { while (TRUE) { EnterCriticalSection(&cs2); printf("\n線(xiàn)程2占用臨界區2"); EnterCriticalSection(&cs1); printf("\n線(xiàn)程2占用臨界區1");
printf("\n線(xiàn)程2占用兩個(gè)臨界區");
LeaveCriticalSection(&cs1); LeaveCriticalSection(&cs2);
printf("\n線(xiàn)程2釋放兩個(gè)臨界區"); Sleep(20); }; } |
運行這個(gè)程序,在中途一旦發(fā)生這樣的輸出:
線(xiàn)程1占用臨界區1
線(xiàn)程2占用臨界區2
或
線(xiàn)程2占用臨界區2
線(xiàn)程1占用臨界區1
或
線(xiàn)程1占用臨界區2
線(xiàn)程2占用臨界區1
或
線(xiàn)程2占用臨界區1
線(xiàn)程1占用臨界區2
程序就"死"掉了,再也運行不下去。因為這樣的輸出,意味著(zhù)兩個(gè)線(xiàn)程相互等待對方釋放臨界區,也即出現了死鎖。
如果我們將線(xiàn)程2的控制函數改為:
long WINAPI ThreadFn(long lParam) { while (TRUE) { EnterCriticalSection(&cs1); printf("\n線(xiàn)程2占用臨界區1"); EnterCriticalSection(&cs2); printf("\n線(xiàn)程2占用臨界區2");
printf("\n線(xiàn)程2占用兩個(gè)臨界區");
LeaveCriticalSection(&cs1); LeaveCriticalSection(&cs2);
printf("\n線(xiàn)程2釋放兩個(gè)臨界區"); Sleep(20); }; } |
再次運行程序,死鎖被消除,程序不再擋掉。這是因為我們改變了線(xiàn)程2中獲得臨界區1、2的順序,消除了線(xiàn)程1、2相互等待資源的可能性。
由此我們得出結論,在使用線(xiàn)程間的同步機制時(shí),要特別留心死鎖的發(fā)生。 深入淺出Win32多線(xiàn)程設計之MFC的多線(xiàn)程 1、創(chuàng )建和終止線(xiàn)程 在MFC程序中創(chuàng )建一個(gè)線(xiàn)程,宜調用AfxBeginThread函數。該函數因參數不同而具有兩種重載版本,分別對應工作者線(xiàn)程和用戶(hù)接口(UI)線(xiàn)程。 工作者線(xiàn)程 CWinThread *AfxBeginThread( AFX_THREADPROC pfnThreadProc, //控制函數 LPVOID pParam, //傳遞給控制函數的參數 int nPriority = THREAD_PRIORITY_NORMAL, //線(xiàn)程的優(yōu)先級 UINT nStackSize = 0, //線(xiàn)程的堆棧大小 DWORD dwCreateFlags = 0, //線(xiàn)程的創(chuàng )建標志 LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL //線(xiàn)程的安全屬性 ); |
工作者線(xiàn)程編程較為簡(jiǎn)單,只需編寫(xiě)線(xiàn)程控制函數和啟動(dòng)線(xiàn)程即可。下面的代碼給出了定義一個(gè)控制函數和啟動(dòng)它的過(guò)程: //線(xiàn)程控制函數 UINT MfcThreadProc(LPVOID lpParam) { CExampleClass *lpObject = (CExampleClass*)lpParam; if (lpObject == NULL || !lpObject->IsKindof(RUNTIME_CLASS(CExampleClass))) return - 1; //輸入參數非法 //線(xiàn)程成功啟動(dòng) while (1) { ...// } return 0; }
//在MFC程序中啟動(dòng)線(xiàn)程 AfxBeginThread(MfcThreadProc, lpObject); |
UI線(xiàn)程 創(chuàng )建用戶(hù)界面線(xiàn)程時(shí),必須首先從CWinThread 派生類(lèi),并使用 DECLARE_DYNCREATE 和 IMPLEMENT_DYNCREATE 宏聲明此類(lèi)。 下面給出了CWinThread類(lèi)的原型(添加了關(guān)于其重要函數功能和是否需要被繼承類(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 //執行線(xiàn)程實(shí)例初始化,必須重寫(xiě) virtual BOOL InitInstance();
// running and idle processing //控制線(xiàn)程的函數,包含消息泵,一般不重寫(xiě) virtual int Run();
//消息調度到TranslateMessage和DispatchMessage之前對其進(jìn)行篩選, //通常不重寫(xiě) virtual BOOL PreTranslateMessage(MSG* pMsg);
virtual BOOL PumpMessage(); // low level message pump
//執行線(xiàn)程特定的閑置時(shí)間處理,通常不重寫(xiě) virtual BOOL OnIdle(LONG lCount); // return TRUE if more idle processing virtual BOOL IsIdleMessage(MSG* pMsg); // checks for special messages
//線(xiàn)程終止時(shí)執行清除,通常需要重寫(xiě) virtual int ExitInstance(); // default will 'delete this'
//截獲由線(xiàn)程的消息和命令處理程序引發(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線(xiàn)程的AfxBeginThread函數的原型為: 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)向導定義一個(gè)繼承自CWinThread的用戶(hù)線(xiàn)程類(lèi)。下面給出產(chǎn)生我們自定義的CWinThread子類(lèi)CMyUIThread的方法。 打開(kāi)VC++ 6.0類(lèi)向導,在如下窗口中選擇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線(xiàn)程: CMyUIThread *pThread; pThread = (CMyUIThread*) AfxBeginThread( RUNTIME_CLASS(CMyUIThread) ); |
另外,我們也可以不用AfxBeginThread 創(chuàng )建線(xiàn)程,而是分如下兩步完成: ?。?)調用線(xiàn)程類(lèi)的構造函數創(chuàng )建一個(gè)線(xiàn)程對象; ?。?)調用CWinThread::CreateThread函數來(lái)啟動(dòng)該線(xiàn)程。 在線(xiàn)程自身內調用AfxEndThread函數可以終止該線(xiàn)程: void AfxEndThread( UINT nExitCode //the exit code of the thread ); |
對于UI線(xiàn)程而言,如果消息隊列中放入了WM_QUIT消息,將結束線(xiàn)程。 關(guān)于UI線(xiàn)程和工作者線(xiàn)程的分配,最好的做法是:將所有與UI相關(guān)的操作放入主線(xiàn)程,其它的純粹的運算工作交給獨立的數個(gè)工作者線(xiàn)程。 候捷先生早些時(shí)間喜歡為MDI程序的每個(gè)窗口創(chuàng )建一個(gè)線(xiàn)程,他后來(lái)澄清了這個(gè)錯誤。因為如果為MDI程序的每個(gè)窗口都單獨創(chuàng )建一個(gè)線(xiàn)程,在窗口進(jìn)行切換的時(shí)候,將進(jìn)行線(xiàn)程的上下文切換! 2.線(xiàn)程間通信 MFC中定義了繼承自CSyncObject類(lèi)的CCriticalSection 、CCEvent、CMutex、CSemaphore類(lèi)封裝和簡(jiǎn)化了WIN32 API所提供的臨界區、事件、互斥和信號量。使用這些同步機制,必須包含"Afxmt.h"頭文件。下圖給出了類(lèi)的繼承關(guān)系: 作為CSyncObject類(lèi)的繼承類(lèi),我們僅僅使用基類(lèi)CSyncObject的接口函數就可以方便、統一的操作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è)函數是Lock和Unlock,若我們直接使用CSyncObject類(lèi)及其派生類(lèi),我們需要非常小心地在Lock之后調用Unlock。 MFC提供的另兩個(gè)類(lèi)CSingleLock(等待一個(gè)對象)和CMultiLock(等待多個(gè)對象)為我們編寫(xiě)應用程序提供了更靈活的機制,下面以實(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對Windows GDI相關(guān)對象進(jìn)行保護的方法,下面再給出一個(gè)其他方面的例子: int array1[10], array2[10]; CMutexSection section; //創(chuàng )建一個(gè)CMutex類(lèi)的對象
//賦值線(xiàn)程控制函數 UINT EvaluateThread(LPVOID param) { CSingleLock singlelock; singlelock(§ion);
//互斥區域 singlelock.Lock(); for (int i = 0; i < 10; i++) array1[i] = i; singlelock.Unlock(); } //拷貝線(xiàn)程控制函數 UINT CopyThread(LPVOID param) { CSingleLock singlelock; singlelock(§ion);
//互斥區域 singlelock.Lock(); for (int i = 0; i < 10; i++) array2[i] = array1[i]; singlelock.Unlock(); } }
AfxBeginThread(EvaluateThread, NULL); //啟動(dòng)賦值線(xiàn)程 AfxBeginThread(CopyThread, NULL); //啟動(dòng)拷貝線(xiàn)程 |
上面的例子中啟動(dòng)了兩個(gè)線(xiàn)程EvaluateThread和CopyThread,線(xiàn)程EvaluateThread把10個(gè)數賦值給數組array1[],線(xiàn)程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作為線(xiàn)程間同步通信的方式以外,我們還可以利用PostThreadMessage函數在線(xiàn)程間發(fā)送消息: BOOL PostThreadMessage(DWORD idThread, // thread identifier UINT Msg, // message to post WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); |
3.線(xiàn)程與消息隊列 在WIN32中,每一個(gè)線(xiàn)程都對應著(zhù)一個(gè)消息隊列。由于一個(gè)線(xiàn)程可以產(chǎn)生數個(gè)窗口,所以并不是每個(gè)窗口都對應著(zhù)一個(gè)消息隊列。下列幾句話(huà)應該作為"定理"被記?。?br> "定理" 一 所有產(chǎn)生給某個(gè)窗口的消息,都先由創(chuàng )建這個(gè)窗口的線(xiàn)程處理; "定理" 二 Windows屏幕上的每一個(gè)控件都是一個(gè)窗口,有對應的窗口函數。 消息的發(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è)函數原型中的四個(gè)參數的意義相同,但是SendMessage和PostMessage的行為有差異。SendMessage必須等待消息被處理后才返回,而PostMessage僅僅將消息放入消息隊列。SendMessage的目標窗口如果屬于另一個(gè)線(xiàn)程,則會(huì )發(fā)生線(xiàn)程上下文切換,等待另一線(xiàn)程處理完成消息。為了防止另一線(xiàn)程當掉,導致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線(xiàn)程、消息隊列與MFC程序的"生死因果" 分析MFC程序的主線(xiàn)程啟動(dòng)及消息隊列處理的過(guò)程將有助于我們進(jìn)一步理解UI線(xiàn)程與消息隊列的關(guān)系,為此我們需要簡(jiǎn)單地敘述一下MFC程序的"生死因果"(侯捷:《深入淺出MFC》)。 使用VC++ 6.0的向導完成一個(gè)最簡(jiǎn)單的單文檔架構MFC應用程序MFCThread: ?。?) 輸入MFC EXE工程名MFCThread; ?。?) 選擇單文檔架構,不支持Document/View結構; ?。?) ActiveX、3D container等其他選項都選擇無(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í)現的類(lèi)CMFCThreadApp繼承自CWinApp類(lèi),而CWinApp類(lèi)又繼承自CWinThread類(lèi)(CWinThread類(lèi)又繼承自CCmdTarget類(lèi)),所以CMFCThread本質(zhì)上是一個(gè)MFC線(xiàn)程類(lèi),下圖給出了相關(guān)的類(lèi)層次結構: 我們提取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 所完成的工作現在由CWinApp 的三個(gè)函數完成: virtual BOOL InitApplication(); virtual BOOL InitInstance(); virtual int Run(); |
"CMFCThreadApp theApp;"語(yǔ)句定義的全局變量theApp是整個(gè)程式的application object,每一個(gè)MFC 應用程序都有一個(gè)。當我們執行MFCThread程序的時(shí)候,這個(gè)全局變量被構造。theApp 配置完成后,WinMain開(kāi)始執行。但是程序中并沒(méi)有WinMain的代碼,它在哪里呢?原來(lái)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; } |
我們提取主干,實(shí)際上,這個(gè)函數做的事情主要是: CWinThread* pThread = AfxGetThread(); CWinApp* pApp = AfxGetApp(); AfxWinInit(hInstance, hPrevInstance, lpCmdLine, nCmdShow) pApp->InitApplication() pThread->InitInstance() pThread->Run(); |
其中,InitApplication 是注冊窗口類(lèi)別的場(chǎng)所;InitInstance是產(chǎn)生窗口并顯示窗口的場(chǎng)所;Run是提取并分派消息的場(chǎng)所。這樣,MFC就同WIN32 SDK程序對應起來(lái)了。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狀態(tài),整個(gè)RUN的執行提取主干就是: do { ::GetMessage(&msg,...); PreTranslateMessage{&msg); ::TranslateMessage(&msg); ::DispatchMessage(&msg); ... } while (::PeekMessage(...)); |
由此,我們建立了MFC消息獲取和派生機制與WIN32 SDK程序之間的對應關(guān)系。下面繼續分析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)匹配對應的消息處理函數,完成整個(gè)消息的"繞行"。 看到這里相信你有這樣的疑問(wèn):程序定義了CWinApp類(lèi)的theApp全局變量,可是從來(lái)沒(méi)有調用AfxBeginThread或theApp.CreateThread啟動(dòng)線(xiàn)程呀,theApp對應的線(xiàn)程是怎么啟動(dòng)的? 答:MFC在這里用了很高明的一招。實(shí)際上,程序開(kāi)始運行,第一個(gè)線(xiàn)程是由操作系統(OS)啟動(dòng)的,在CWinApp的構造函數里,MFC將theApp"對應"向了這個(gè)線(xiàn)程,具體的實(shí)現是這樣的: 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啟動(dòng)的這個(gè)當前線(xiàn)程相關(guān)的值,如代碼: m_hThread = ::GetCurrentThread();//theApp的線(xiàn)程句柄等于當前線(xiàn)程句柄 m_nThreadID = ::GetCurrentThreadId();//theApp的線(xiàn)程ID等于當前線(xiàn)程ID |
所以CWinApp類(lèi)幾乎只是為MFC程序的第一個(gè)線(xiàn)程量身定制的,它不需要也不能被AfxBeginThread或theApp.CreateThread"再次"啟動(dòng)。這就是CWinApp類(lèi)和theApp全局變量的內涵!如果你要再增加一個(gè)UI線(xiàn)程,不要繼承類(lèi)CWinApp,而應繼承類(lèi)CWinThread。而參考第1節,由于我們一般以主線(xiàn)程(在MFC程序里實(shí)際上就是OS啟動(dòng)的第一個(gè)線(xiàn)程)處理所有窗口的消息,所以我們幾乎沒(méi)有再啟動(dòng)UI線(xiàn)程的需求! 深入淺出Win32多線(xiàn)程程序設計之綜合實(shí)例 本章我們將以工業(yè)控制和嵌入式系統中運用極為廣泛的串口通信為例講述多線(xiàn)程的典型應用。
而網(wǎng)絡(luò )通信也是多線(xiàn)程應用最廣泛的領(lǐng)域之一,所以本章的最后一節也將對多線(xiàn)程網(wǎng)絡(luò )通信進(jìn)行簡(jiǎn)短的描述。
1.串口通信
在工業(yè)控制系統中,工控機(一般都基于PC Windows平臺)經(jīng)常需要與單片機通過(guò)串口進(jìn)行通信。因此,操作和使用PC的串口成為大多數單片機、嵌入式系統領(lǐng)域工程師必須具備的能力。
串口的使用需要通過(guò)三個(gè)步驟來(lái)完成的:
?。?) 打開(kāi)通信端口;
?。?) 初始化串口,設置波特率、數據位、停止位、奇偶校驗等參數。為了給讀者一個(gè)直觀(guān)的印象,下圖從Windows的"控制面板->系統->設備管理器->通信端口(COM1)"打開(kāi)COM的設置窗口:
?。?) 讀寫(xiě)串口。
在WIN32平臺下,對通信端口進(jìn)行操作跟基本的文件操作一樣。
創(chuàng )建/打開(kāi)COM資源
下列函數如果調用成功,則返回一個(gè)標識通信端口的句柄,否則返回-1:
HADLE CreateFile(PCTSTR lpFileName, //通信端口名,如"COM1" WORD dwDesiredAccess, //對資源的訪(fǎng)問(wèn)類(lèi)型 WORD dwShareMode, //指定共享模式,COM不能共享,該參數為0 PSECURITY_ATTRIBUTES lpSecurityAttributes, //安全描述符指針,可為NULL WORD dwCreationDisposition, //創(chuàng )建方式 WORD dwFlagsAndAttributes, //文件屬性,可為NULL HANDLE hTemplateFile //模板文件句柄,置為NULL ); |
獲得/設置COM屬性
下列函數可以獲得COM口的設備控制塊,從而獲得相關(guān)參數:
BOOL WINAPI GetCommState( HANDLE hFile, //標識通信端口的句柄 LPDCB lpDCB //指向一個(gè)設備控制塊(DCB結構)的指針 ); |
如果要調整通信端口的參數,則需要重新配置設備控制塊,再用WIN32 API SetCommState()函數進(jìn)行設置:
BOOL SetCommState( HANDLE hFile, //標識通信端口的句柄 LPDCB lpDCB //指向一個(gè)設備控制塊(DCB結構)的指針 ); |
DCB結構包含了串口的各項參數設置,如下:
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; |
讀寫(xiě)串口
在讀寫(xiě)串口之前,還要用PurgeComm()函數清空緩沖區,并用SetCommMask ()函數設置事件掩模來(lái)監視指定通信端口上的事件,其原型為:
BOOL SetCommMask( HANDLE hFile, //標識通信端口的句柄 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. |
在設置好事件掩模后,我們就可以利用WaitCommEvent()函數來(lái)等待串口上發(fā)生事件,其函數原型為:
BOOL WaitCommEvent( HANDLE hFile, //標識通信端口的句柄 LPDWORD lpEvtMask, //指向存放事件標識變量的指針 LPOVERLAPPED lpOverlapped, // 指向overlapped結構 ); |
我們可以在發(fā)生事件后,根據相應的事件類(lèi)型,進(jìn)行串口的讀寫(xiě)操作:
BOOL ReadFile(HANDLE hFile, //標識通信端口的句柄 LPVOID lpBuffer, //輸入數據Buffer指針 DWORD nNumberOfBytesToRead, // 需要讀取的字節數 LPDWORD lpNumberOfBytesRead, //實(shí)際讀取的字節數指針 LPOVERLAPPED lpOverlapped //指向overlapped結構 ); BOOL WriteFile(HANDLE hFile, //標識通信端口的句柄 LPCVOID lpBuffer, //輸出數據Buffer指針 DWORD nNumberOfBytesToWrite, //需要寫(xiě)的字節數 LPDWORD lpNumberOfBytesWritten, //實(shí)際寫(xiě)入的字節數指針 LPOVERLAPPED lpOverlapped //指向overlapped結構 ); | 2.工程實(shí)例
下面我們用第1節所述API實(shí)現一個(gè)多線(xiàn)程的串口通信程序。這個(gè)例子工程(工程名為MultiThreadCom)的界面很簡(jiǎn)單,如下圖所示:
它是一個(gè)多線(xiàn)程的應用程序,包括兩個(gè)工作者線(xiàn)程,分別處理串口1和串口2。為了簡(jiǎn)化問(wèn)題,我們讓連接兩個(gè)串口的電纜只包含RX、TX兩根連線(xiàn)(即不以硬件控制RS-232,串口上只會(huì )發(fā)生EV_TXEMPTY、EV_RXCHAR事件)。
在工程實(shí)例的BOOL CMultiThreadComApp::InitInstance()函數中,啟動(dòng)并設置COM1和COM2,其源代碼為:
BOOL CMultiThreadComApp::InitInstance() { AfxEnableControlContainer(); //打開(kāi)并設置COM1 hComm1=CreateFile("COM1", GENERIC_READ|GENERIC_WRITE, 0, NULL ,OPEN_EXISTING, 0,NULL); if (hComm1==(HANDLE)-1) { AfxMessageBox("打開(kāi)COM1失敗"); return false; } else { DCB wdcb; GetCommState (hComm1,&wdcb); wdcb.BaudRate=9600; SetCommState (hComm1,&wdcb); PurgeComm(hComm1,PURGE_TXCLEAR); } //打開(kāi)并設置COM2 hComm2=CreateFile("COM2", GENERIC_READ|GENERIC_WRITE, 0, NULL ,OPEN_EXISTING, 0,NULL); if (hComm2==(HANDLE)-1) { AfxMessageBox("打開(kāi)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; } |
此后我們在對話(huà)框CMultiThreadComDlg的初始化函數OnInitDialog中啟動(dòng)兩個(gè)分別處理COM1和COM2的線(xiàn)程:
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處理線(xiàn)程 DWORD nThreadId1; hCommThread1 = ::CreateThread((LPSECURITY_ATTRIBUTES)NULL, 0, (LPTHREAD_START_ROUTINE)Com1ThreadProcess, AfxGetMainWnd()->m_hWnd, 0, &nThreadId1); if (hCommThread1 == NULL) { AfxMessageBox("創(chuàng )建串口1處理線(xiàn)程失敗"); return false; } //啟動(dòng)串口2處理線(xiàn)程 DWORD nThreadId2; hCommThread2 = ::CreateThread((LPSECURITY_ATTRIBUTES)NULL, 0, (LPTHREAD_START_ROUTINE)Com2ThreadProcess, AfxGetMainWnd()->m_hWnd, 0, &nThreadId2); if (hCommThread2 == NULL) { AfxMessageBox("創(chuàng )建串口2處理線(xiàn)程失敗"); return false; }
return TRUE; // return TRUE unless you set the focus to a control } |
兩個(gè)串口COM1和COM2對應的線(xiàn)程處理函數等待串口上發(fā)生事件,并根據事件類(lèi)型和自身緩沖區是否有數據要發(fā)送進(jìn)行相應的處理,其源代碼為:
DWORD WINAPI Com1ThreadProcess(HWND hWnd//主窗口句柄) { DWORD wEven; char str[10]; //讀入數據 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寫(xiě)入數據 DWORD wCount; //寫(xiě)入的字節數 WriteFile(hComm1, com1Data.TxBuf[wTxPos], 1, &wCount, NULL); com1Data.wTxPos++; } break; case EV_RXCHAR: if (com1Data.wRxPos < com1Data.wRxLen) { //讀取串口數據, 處理收到的數據 DWORD wCount; //讀取的字節數 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]; //讀入數據 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寫(xiě)入數據 DWORD wCount; //寫(xiě)入的字節數 WriteFile(hComm2, com2Data.TxBuf[wTxPos], 1, &wCount, NULL); com2Data.wTxPos++; } break; case EV_RXCHAR: if (com2Data.wRxPos < com2Data.wRxLen) { //讀取串口數據, 處理收到的數據 DWORD wCount; //讀取的字節數 ReadFile(hComm2, com2Data.RxBuf[wRxPos], 1, &wCount, NULL); com2Data.wRxPos++; if(com2Data.wRxPos== com2Data.wRxLen); ::PostMessage(hWnd, COM_SENDCHAR, 0, 1); } break; } } } return TRUE; } |
線(xiàn)程控制函數中所操作的com1Data和com2Data是與串口對應的數據結構struct tagSerialPort的實(shí)例,這個(gè)數據結構是:
typedef struct tagSerialPort { BYTE RxBuf[SPRX_BUFLEN];//接收Buffer WORD wRxPos; //當前接收字節位置 WORD wRxLen; //要接收的字節數 BYTE TxBuf[SPTX_BUFLEN];//發(fā)送Buffer WORD wTxPos; //當前發(fā)送字節位置 WORD wTxLen; //要發(fā)送的字節數 }SerialPort, * LPSerialPort; | 3.多線(xiàn)程串口類(lèi)
使用多線(xiàn)程串口通信更方便的途徑是編寫(xiě)一個(gè)多線(xiàn)程的串口類(lèi),例如Remon Spekreijse編寫(xiě)了一個(gè)CSerialPort串口類(lèi)。仔細分析這個(gè)類(lèi)的源代碼,將十分有助于我們對先前所學(xué)多線(xiàn)程及同步知識的理解。
3.1類(lèi)的定義
#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類(lèi)的實(shí)現
3.2.1構造函數與析構函數
進(jìn)行相關(guān)變量的賦初值及內存恢復:
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核心函數:初始化串口
在初始化串口函數中,將打開(kāi)串口,設置相關(guān)參數,并創(chuàng )建串口相關(guān)的用戶(hù)控制事件,初始化臨界區(Critical Section),以成隊的EnterCriticalSection()、LeaveCriticalSection()函數進(jìn)行資源的排它性訪(fǎng)問(wè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核心函數:串口線(xiàn)程控制函數
串口線(xiàn)程處理函數是整個(gè)類(lèi)中最核心的部分,它主要完成兩類(lèi)工作:
?。?)利用WaitCommEvent函數對串口上發(fā)生的事件進(jìn)行獲取并根據事件的不同類(lèi)型進(jìn)行相應的處理;
?。?)利用WaitForMultipleObjects函數對串口相關(guān)的用戶(hù)控制事件進(jìn)行等待并做相應處理。
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è)函數用于對串口線(xiàn)程進(jìn)行啟動(dòng)、掛起和恢復:
// // 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讀寫(xiě)串口
下面一組函數是用戶(hù)對串口進(jìn)行讀寫(xiě)操作的接口:
// // 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控制接口
應用程序員使用下列一組public函數可以獲取串口的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錯誤處理
// // 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; } |
仔細分析Remon Spekreijse的CSerialPort類(lèi)對我們理解多線(xiàn)程及其同步機制是大有益處的,從http://codeguru.earthweb.com/network/serialport.shtml我們可以獲取CSerialPort類(lèi)的介紹與工程實(shí)例。另外,電子工業(yè)出版社《Visual C++/Turbo C串口通信編程實(shí)踐》一書(shū)的作者龔建偉也編寫(xiě)了一個(gè)使用CSerialPort類(lèi)的例子,可以從http://www.gjwtech.com/scomm/sc2serialportclass.htm獲得詳情。
4.多線(xiàn)程網(wǎng)絡(luò )通信
在網(wǎng)絡(luò )通信中使用多線(xiàn)程主要有兩種途徑,即主監控線(xiàn)程和線(xiàn)程池。
4.1主監控線(xiàn)程
這種方式指的是程序中使用一個(gè)主線(xiàn)程監控某特定端口,一旦在這個(gè)端口上發(fā)生連接請求,則主監控線(xiàn)程動(dòng)態(tài)使用CreateThread派生出新的子線(xiàn)程處理該請求。主線(xiàn)程在派生子線(xiàn)程后不再對子線(xiàn)程加以控制和調度,而由子線(xiàn)程獨自和客戶(hù)方發(fā)生連接并處理異常。
使用這種方法的優(yōu)點(diǎn)是:
?。?)可以較快地實(shí)現原型設計,尤其在用戶(hù)數目較少、連接保持時(shí)間較長(cháng)時(shí)有表現較好;
?。?)主線(xiàn)程不與子線(xiàn)程發(fā)生通信,在一定程度上減少了系統資源的消耗。
其缺點(diǎn)是:
?。?)生成和終止子線(xiàn)程的開(kāi)銷(xiāo)比較大;
?。?)對遠端用戶(hù)的控制較弱。
這種多線(xiàn)程方式總的特點(diǎn)是"動(dòng)態(tài)生成,靜態(tài)調度"。
4.2線(xiàn)程池
這種方式指的是主線(xiàn)程在初始化時(shí)靜態(tài)地生成一定數量的懸掛子線(xiàn)程,放置于線(xiàn)程池中。隨后,主線(xiàn)程將對這些懸掛子線(xiàn)程進(jìn)行動(dòng)態(tài)調度。一旦客戶(hù)發(fā)出連接請求,主線(xiàn)程將從線(xiàn)程池中查找一個(gè)懸掛的子線(xiàn)程:
?。?)如果找到,主線(xiàn)程將該連接分配給這個(gè)被發(fā)現的子線(xiàn)程。子線(xiàn)程從主線(xiàn)程處接管該連接,并與用戶(hù)通信。當連接結束時(shí),該子線(xiàn)程將自動(dòng)懸掛,并進(jìn)人線(xiàn)程池等待再次被調度;
?。?)如果當前已沒(méi)有可用的子線(xiàn)程,主線(xiàn)程將通告發(fā)起連接的客戶(hù)。
使用這種方法進(jìn)行設計的優(yōu)點(diǎn)是:
?。?)主線(xiàn)程可以更好地對派生的子線(xiàn)程進(jìn)行控制和調度;
?。?)對遠程用戶(hù)的監控和管理能力較強。
雖然主線(xiàn)程對子線(xiàn)程的調度要消耗一定的資源,但是與主監控線(xiàn)程方式中派生和終止線(xiàn)程所要耗費的資源相比,要少很多。因此,使用該種方法設計和實(shí)現的系統在客戶(hù)端連接和終止變更頻繁時(shí)有上佳表現。
這種多線(xiàn)程方式總的特點(diǎn)是"靜態(tài)生成,動(dòng)態(tài)調度"。
|
|