從單進(jìn)程單線程到多進(jìn)程多線程是操作系統(tǒng)發(fā)展的一種必然趨勢(shì),當(dāng)年的DOS系統(tǒng)屬于單任務(wù)操作系統(tǒng),最優(yōu)秀的程序員也只能通過(guò)駐留內(nèi)存的方式實(shí)現(xiàn)所謂的"多任務(wù)",而如今的Win32操作系統(tǒng)卻可以一邊聽(tīng)音樂(lè),一邊編程,一邊打印文檔。 理解多線程及其同步、互斥等通信方式是理解現(xiàn)代操作系統(tǒng)的關(guān)鍵一環(huán),當(dāng)我們精通了Win32多線程程序設(shè)計(jì)后,理解和學(xué)習(xí)其它操作系統(tǒng)的多任務(wù)控制也非常容易。因此,學(xué)習(xí)Win32多線程不僅對(duì)理解Win32本身有重要意義,而且對(duì)學(xué)習(xí)和領(lǐng)會(huì)其它操作系統(tǒng)也有觸類(lèi)旁通的作用。
深入淺出Win32多線程程序設(shè)計(jì)之基本概念 引言
從單進(jìn)程單線程到多進(jìn)程多線程是操作系統(tǒng)發(fā)展的一種必然趨勢(shì),當(dāng)年的DOS系統(tǒng)屬于單任務(wù)操作系統(tǒng),最優(yōu)秀的程序員也只能通過(guò)駐留內(nèi)存的方式實(shí)現(xiàn)所謂的"多任務(wù)",而如今的Win32操作系統(tǒng)卻可以一邊聽(tīng)音樂(lè),一邊編程,一邊打印文檔。
理解多線程及其同步、互斥等通信方式是理解現(xiàn)代操作系統(tǒng)的關(guān)鍵一環(huán),當(dāng)我們精通了Win32多線程程序設(shè)計(jì)后,理解和學(xué)習(xí)其它操作系統(tǒng)的多任務(wù)控制也非常容易。許多程序員從來(lái)沒(méi)有學(xué)習(xí)過(guò)嵌入式系統(tǒng)領(lǐng)域著名的操作系統(tǒng)VxWorks,但是立馬就能在上面做開(kāi)發(fā),大概要?dú)w功于平時(shí)在Win32多線程上下的功夫。
因此,學(xué)習(xí)Win32多線程不僅對(duì)理解Win32本身有重要意義,而且對(duì)學(xué)習(xí)和領(lǐng)會(huì)其它操作系統(tǒng)也有觸類(lèi)旁通的作用。
進(jìn)程與線程
先闡述一下進(jìn)程和線程的概念和區(qū)別,這是一個(gè)許多大學(xué)老師也講不清楚的問(wèn)題。
進(jìn)程(Process)是具有一定獨(dú)立功能的程序關(guān)于某個(gè)數(shù)據(jù)集合上的一次運(yùn)行活動(dòng),是系統(tǒng)進(jìn)行資源分配和調(diào)度的一個(gè)獨(dú)立單位。程序只是一組指令的有序集合,它本身沒(méi)有任何運(yùn)行的含義,只是一個(gè)靜態(tài)實(shí)體。而進(jìn)程則不同,它是程序在某個(gè)數(shù)據(jù)集上的執(zhí)行,是一個(gè)動(dòng)態(tài)實(shí)體。它因創(chuàng)建而產(chǎn)生,因調(diào)度而運(yùn)行,因等待資源或事件而被處于等待狀態(tài),因完成任務(wù)而被撤消,反映了一個(gè)程序在一定的數(shù)據(jù)集上運(yùn)行的全部動(dòng)態(tài)過(guò)程。
線程(Thread)是進(jìn)程的一個(gè)實(shí)體,是CPU調(diào)度和分派的基本單位。線程不能夠獨(dú)立執(zhí)行,必須依存在應(yīng)用程序中,由應(yīng)用程序提供多個(gè)線程執(zhí)行控制。
線程和進(jìn)程的關(guān)系是:線程是屬于進(jìn)程的,線程運(yùn)行在進(jìn)程空間內(nèi),同一進(jìn)程所產(chǎn)生的線程共享同一內(nèi)存空間,當(dāng)進(jìn)程退出時(shí)該進(jìn)程所產(chǎn)生的線程都會(huì)被強(qiáng)制退出并清除。線程可與屬于同一進(jìn)程的其它線程共享進(jìn)程所擁有的全部資源,但是其本身基本上不擁有系統(tǒng)資源,只擁有一點(diǎn)在運(yùn)行中必不可少的信息(如程序計(jì)數(shù)器、一組寄存器和棧)。
根據(jù)進(jìn)程與線程的設(shè)置,操作系統(tǒng)大致分為如下類(lèi)型:
(1)單進(jìn)程、單線程,MS-DOS大致是這種操作系統(tǒng);
?。?)多進(jìn)程、單線程,多數(shù)UNIX(及類(lèi)UNIX的LINUX)是這種操作系統(tǒng);
?。?)多進(jìn)程、多線程,Win32(Windows
NT/2000/XP等)、Solaris
2.x和OS/2都是這種操作系統(tǒng);
?。?)單進(jìn)程、多線程,VxWorks是這種操作系統(tǒng)。
在操作系統(tǒng)中引入線程帶來(lái)的主要好處是:
?。?)在進(jìn)程內(nèi)創(chuàng)建、終止線程比創(chuàng)建、終止進(jìn)程要快;
?。?)同一進(jìn)程內(nèi)的線程間切換比進(jìn)程間的切換要快,尤其是用戶(hù)級(jí)線程間的切換。另外,線程的出現(xiàn)還因?yàn)橐韵聨讉€(gè)原因:
?。?)并發(fā)程序的并發(fā)執(zhí)行,在多處理環(huán)境下更為有效。一個(gè)并發(fā)程序可以建立一個(gè)進(jìn)程,而這個(gè)并發(fā)程序中的若干并發(fā)程序段就可以分別建立若干線程,使這些線程在不同的處理機(jī)上執(zhí)行。
?。?)每個(gè)進(jìn)程具有獨(dú)立的地址空間,而該進(jìn)程內(nèi)的所有線程共享該地址空間。這樣可以解決父子進(jìn)程模型中,子進(jìn)程必須復(fù)制父進(jìn)程地址空間的問(wèn)題。
(3)線程對(duì)解決客戶(hù)/服務(wù)器模型非常有效。
Win32進(jìn)程
1、進(jìn)程間通信(IPC)
Win32進(jìn)程間通信的方式主要有:
(1)剪貼板(Clip
Board);
(2)動(dòng)態(tài)數(shù)據(jù)交換(Dynamic Data Exchange);
?。?)部件對(duì)象模型(Component
Object Model);
?。?)文件映射(File Mapping);
?。?)郵件槽(Mail
Slots);
?。?)管道(Pipes);
?。?)Win32套接字(Socket);
?。?)遠(yuǎn)程過(guò)程調(diào)用(Remote
Procedure Call);
?。?)WM_COPYDATA消息(WM_COPYDATA
Message)。
2、獲取進(jìn)程信息
在WIN32中,可使用在PSAPI .DLL中提供的Process status
Helper函數(shù)幫助我們獲取進(jìn)程信息。
?。?)EnumProcesses()函數(shù)可以獲取進(jìn)程的ID,其原型為:
BOOL EnumProcesses(DWORD * lpidProcess, DWORD cb,
DWORD*cbNeeded); | 參數(shù)lpidProcess:一個(gè)足夠大的DWORD類(lèi)型的數(shù)組,用于存放進(jìn)程的ID值;
參數(shù)cb:存放進(jìn)程ID值的數(shù)組的最大長(zhǎng)度,是一個(gè)DWORD類(lèi)型的數(shù)據(jù);
參數(shù)cbNeeded:指向一個(gè)DWORD類(lèi)型數(shù)據(jù)的指針,用于返回進(jìn)程的數(shù)目;
函數(shù)返回值:如果調(diào)用成功,返回TRUE,同時(shí)將所有進(jìn)程的ID值存放在lpidProcess參數(shù)所指向的數(shù)組中,進(jìn)程個(gè)數(shù)存放在cbNeeded參數(shù)所指向的變量中;如果調(diào)用失敗,返回FALSE。
?。?)GetModuleFileNameExA()函數(shù)可以實(shí)現(xiàn)通過(guò)進(jìn)程句柄獲取進(jìn)程文件名,其原型為:
DWORD GetModuleFileNameExA(HANDLE hProcess, HMODULE hModule,LPTSTR
lpstrFileName, DWORD
nsize); | 參數(shù)hProcess:接受進(jìn)程句柄的參數(shù),是HANDLE類(lèi)型的變量;
參數(shù)hModule:指針型參數(shù),在本文的程序中取值為NULL;
參數(shù)lpstrFileName:LPTSTR類(lèi)型的指針,用于接受主調(diào)函數(shù)傳遞來(lái)的用于存放進(jìn)程名的字符數(shù)組指針;
參數(shù)nsize:lpstrFileName所指數(shù)組的長(zhǎng)度;
函數(shù)返回值:如果調(diào)用成功,返回一個(gè)大于0的DWORD類(lèi)型的數(shù)據(jù),同時(shí)將hProcess所對(duì)應(yīng)的進(jìn)程名存放在lpstrFileName參數(shù)所指向的數(shù)組中;加果調(diào)用失敗,則返回0。
通過(guò)下列代碼就可以遍歷系統(tǒng)中的進(jìn)程,獲得進(jìn)程列表:
//獲取當(dāng)前進(jìn)程總數(shù) EnumProcesses(process_ids, sizeof(process_ids), &num_processes); //遍歷進(jìn)程 for (int i = 0; i < num_processes; i++) { //根據(jù)進(jìn)程ID獲取句柄 process[i] = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, process_ids[i]); //通過(guò)句柄獲取進(jìn)程文件名 if (GetModuleFileNameExA(process[i], NULL, File_name, sizeof(fileName))) cout << fileName << endl; } Win32線程
WIN32靠線程的優(yōu)先級(jí)(達(dá)到搶占式多任務(wù)的目的)及分配給線程的CPU時(shí)間來(lái)調(diào)度線程。WIN32本身的許多應(yīng)用程序也利用了多線程的特性,如任務(wù)管理器等。
本質(zhì)而言,一個(gè)處理器同一時(shí)刻只能執(zhí)行一個(gè)線程("微觀串行")。WIN32多任務(wù)機(jī)制使得CPU好像在同時(shí)處理多個(gè)任務(wù)一樣,實(shí)現(xiàn)了"宏觀并行"。其多線程調(diào)度的機(jī)制為:
(1)運(yùn)行一個(gè)線程,直到被中斷或線程必須等待到某個(gè)資源可用;
(2)保存當(dāng)前執(zhí)行線程的描述表(上下文);
?。?)裝入下一執(zhí)行線程的描述表(上下文);
?。?)若存在等待被執(zhí)行的線程,則重復(fù)上述過(guò)程。
WIN32下的線程可能具有不同的優(yōu)先級(jí),優(yōu)先級(jí)的范圍為0~31,共32級(jí),其中31表示最高優(yōu)先級(jí),優(yōu)先級(jí)0為系統(tǒng)保留。它們可以分成兩類(lèi),即實(shí)時(shí)優(yōu)先級(jí)和可變優(yōu)先級(jí):
?。?)實(shí)時(shí)優(yōu)先級(jí)從16到31,是實(shí)時(shí)程序所用的高優(yōu)先級(jí)線程,如許多監(jiān)控類(lèi)應(yīng)用程序;
?。?)可變優(yōu)先級(jí)從1到15,絕大多數(shù)程序的優(yōu)先級(jí)都在這個(gè)范圍內(nèi)。。WIN32調(diào)度器為了優(yōu)化系統(tǒng)響應(yīng)時(shí)間,在它們執(zhí)行過(guò)程中可動(dòng)態(tài)調(diào)整它們的優(yōu)先級(jí)。
多線程確實(shí)給應(yīng)用開(kāi)發(fā)帶來(lái)了許多好處,但并非任何情況下都要使用多線程,一定要根據(jù)應(yīng)用程序的具體情況來(lái)綜合考慮。一般來(lái)說(shuō),在以下情況下可以考慮使用多線程:
(1)應(yīng)用程序中的各任務(wù)相對(duì)獨(dú)立;
(2)某些任務(wù)耗時(shí)較多;
?。?)各任務(wù)需要有不同的優(yōu)先級(jí)。
另外,對(duì)于一些實(shí)時(shí)系統(tǒng)應(yīng)用,應(yīng)考慮多線程。
Win32核心對(duì)象
WIN32核心對(duì)象包括進(jìn)程、線程、文件、事件、信號(hào)量、互斥體和管道,核心對(duì)象可能有不只一個(gè)擁有者,甚至可以跨進(jìn)程。有一組WIN32
API與核心對(duì)象息息相關(guān):
(1)WaitForSingleObject,用于等待對(duì)象的"激活",其函數(shù)原型為:
DWORD WaitForSingleObject( HANDLE hHandle, // 等待對(duì)象的句柄 DWORD
dwMilliseconds //
等待毫秒數(shù),INFINITE表示無(wú)限等待 ); | 可以作為WaitForSingleObject第一個(gè)參數(shù)的對(duì)象包括:Change
notification、Console input、Event、Job、Memory resource
notification、Mutex、Process、Semaphore、Thread和Waitable
timer。
如果等待的對(duì)象不可用,那么線程就會(huì)掛起,直到對(duì)象可用線程才會(huì)被喚醒。對(duì)不同的對(duì)象,WaitForSingleObject表現(xiàn)為不同的含義。例如,使用WaitForSingleObject(hThread,…)可以判斷一個(gè)線程是否結(jié)束;使用WaitForSingleObject(hMutex,…)可以判斷是否能夠進(jìn)入臨界區(qū);而WaitForSingleObject
(hProcess,…
)則表現(xiàn)為等待一個(gè)進(jìn)程的結(jié)束。
與WaitForSingleObject對(duì)應(yīng)還有一個(gè)WaitForMultipleObjects函數(shù),可以用于等待多個(gè)對(duì)象,其原型為:
DWORD WaitForMultipleObjects(DWORD nCount,const HANDLE* pHandles,BOOL
bWaitAll,DWORD
dwMilliseconds); | ?。?)CloseHandle,用于關(guān)閉對(duì)象,其函數(shù)原型為:
BOOL CloseHandle(HANDLE
hObject); | 如果函數(shù)執(zhí)行成功,則返回TRUE;否則返回FALSE,我們可以通過(guò)GetLastError函數(shù)進(jìn)一步可以獲得錯(cuò)誤原因。
C運(yùn)行時(shí)庫(kù)
在VC++6.0中,有兩種多線程編程方法:一是使用C運(yùn)行時(shí)庫(kù)及WIN32
API函數(shù),另一種方法是使用MFC,MFC對(duì)多線程開(kāi)發(fā)有強(qiáng)大的支持。 標(biāo)準(zhǔn)C運(yùn)行時(shí)庫(kù)是1970年問(wèn)世的,當(dāng)時(shí)還沒(méi)有多線程的概念。因此,C運(yùn)行時(shí)庫(kù)早期的設(shè)計(jì)者們不可能考慮到讓其支持多線程應(yīng)用程序。 Visual
C++提供了兩種版本的C運(yùn)行時(shí)庫(kù),-個(gè)版本供單線程應(yīng)用程序調(diào)用,另一個(gè)版本供多線程應(yīng)用程序調(diào)用。多線程運(yùn)行時(shí)庫(kù)與單線程運(yùn)行時(shí)庫(kù)有兩個(gè)重大差別:
(1)類(lèi)似errno的全局變量,每個(gè)線程單獨(dú)設(shè)置一個(gè);
這樣從每個(gè)線程中可以獲取正確的錯(cuò)誤信息。
(2)多線程庫(kù)中的數(shù)據(jù)結(jié)構(gòu)以同步機(jī)制加以保護(hù)。
這樣可以避免訪問(wèn)時(shí)候的沖突。
Visual
C++提供的多線程運(yùn)行時(shí)庫(kù)又分為靜態(tài)鏈接庫(kù)和動(dòng)態(tài)鏈接庫(kù)兩類(lèi),而每一類(lèi)運(yùn)行時(shí)庫(kù)又可再分為debug版和release版,因此Visual
C++共提供了6個(gè)運(yùn)行時(shí)庫(kù)。如下表:
C運(yùn)行時(shí)庫(kù) |
庫(kù)文件 |
Single thread(static link) |
libc.lib |
Debug single thread(static link) |
Libcd.lib |
MultiThread(static link) |
libcmt.lib |
Debug multiThread(static link) |
libcmtd.lib |
MultiThread(dynamic link) |
msvert.lib |
Debug multiThread(dynamic link) |
msvertd.lib | 如果不使用VC多線程C運(yùn)行時(shí)庫(kù)來(lái)生成多線程程序,必須執(zhí)行下列操作:
?。?)使用標(biāo)準(zhǔn)
C 庫(kù)(基于單線程)并且只允許可重入函數(shù)集進(jìn)行庫(kù)調(diào)用;
(2)使用 Win32 API 線程管理函數(shù),如
CreateThread;
?。?)通過(guò)使用 Win32 服務(wù)(如信號(hào)量和 EnterCriticalSection 及
LeaveCriticalSection 函數(shù)),為不可重入的函數(shù)提供自己的同步。
如果使用標(biāo)準(zhǔn) C
庫(kù)而調(diào)用VC運(yùn)行時(shí)庫(kù)函數(shù),則在程序的link階段會(huì)提示如下錯(cuò)誤:
error LNK2001: unresolved external symbol __endthreadex error LNK2001:
unresolved external symbol __beginthreadex | 深入淺出Win32多線程程序設(shè)計(jì)之線程控制 WIN32線程控制主要實(shí)現(xiàn)線程的創(chuàng)建、終止、掛起和恢復(fù)等操作,這些操作都依賴(lài)于WIN32提供的一組API和具體編譯器的C運(yùn)行時(shí)庫(kù)函數(shù)。
1.線程函數(shù)
在啟動(dòng)一個(gè)線程之前,必須為線程編寫(xiě)一個(gè)全局的線程函數(shù),這個(gè)線程函數(shù)接受一個(gè)32位的LPVOID作為參數(shù),返回一個(gè)UINT,線程函數(shù)的結(jié)構(gòu)為:
UINT ThreadFunction(LPVOID
pParam) { //線程處理代碼 return0; } | 在線程處理代碼部分通常包括一個(gè)死循環(huán),該循環(huán)中先等待某事情的發(fā)生,再處理相關(guān)的工作:
while(1) { WaitForSingleObject(…,…);//或WaitForMultipleObjects(…) //Do
something } | 一般來(lái)說(shuō),C++的類(lèi)成員函數(shù)不能作為線程函數(shù)。這是因?yàn)樵陬?lèi)中定義的成員函數(shù),編譯器會(huì)給其加上this指針。請(qǐng)看下列程序:
#include "windows.h" #include <process.h> class ExampleTask
{ public: void taskmain(LPVOID param); void StartTask();
}; void ExampleTask::taskmain(LPVOID param) {}
void
ExampleTask::StartTask() { _beginthread(taskmain,0,NULL); }
int main(int argc, char* argv[]) { ExampleTask
realTimeTask; realTimeTask.StartTask(); return
0; } | 程序編譯時(shí)出現(xiàn)如下錯(cuò)誤:
error C2664: '_beginthread' : cannot convert parameter 1 from 'void (void
*)' to 'void (__cdecl *)(void *)' None of the functions with this name in
scope match the target type | 再看下列程序:
#include "windows.h" #include <process.h> class ExampleTask
{ public: void taskmain(LPVOID param); };
void
ExampleTask::taskmain(LPVOID param) {}
int main(int argc, char*
argv[]) { ExampleTask
realTimeTask; _beginthread(ExampleTask::taskmain,0,NULL); return
0; } | 程序編譯時(shí)會(huì)出錯(cuò):
error C2664: '_beginthread' : cannot convert parameter 1 from 'void (void
*)' to 'void (__cdecl *)(void *)' None of the functions with this name in
scope match the target
type | 如果一定要以類(lèi)成員函數(shù)作為線程函數(shù),通常有如下解決方案:
(1)將該成員函數(shù)聲明為static類(lèi)型,去掉this指針;
我們將上述二個(gè)程序改變?yōu)椋?br>
#include "windows.h" #include <process.h> class ExampleTask
{ public: void static taskmain(LPVOID param); void
StartTask(); };
void ExampleTask::taskmain(LPVOID param) {}
void ExampleTask::StartTask() {
_beginthread(taskmain,0,NULL); }
int main(int argc, char*
argv[]) { ExampleTask
realTimeTask; realTimeTask.StartTask(); return 0; } 和 #include
"windows.h" #include <process.h> class ExampleTask {
public: void static taskmain(LPVOID param); };
void
ExampleTask::taskmain(LPVOID param) {}
int main(int argc, char*
argv[]) { _beginthread(ExampleTask::taskmain,0,NULL); return
0; } | 均編譯通過(guò)。
將成員函數(shù)聲明為靜態(tài)雖然可以解決作為線程函數(shù)的問(wèn)題,但是它帶來(lái)了新的問(wèn)題,那就是static成員函數(shù)只能訪問(wèn)static成員。解決此問(wèn)題的一種途徑是可以在調(diào)用類(lèi)靜態(tài)成員函數(shù)(線程函數(shù))時(shí)將this指針作為參數(shù)傳入,并在改線程函數(shù)中用強(qiáng)制類(lèi)型轉(zhuǎn)換將this轉(zhuǎn)換成指向該類(lèi)的指針,通過(guò)該指針訪問(wèn)非靜態(tài)成員。
(2)不定義類(lèi)成員函數(shù)為線程函數(shù),而將線程函數(shù)定義為類(lèi)的友元函數(shù)。這樣,線程函數(shù)也可以有類(lèi)成員函數(shù)同等的權(quán)限;
我們將程序修改為:
#include "windows.h" #include <process.h> class ExampleTask
{ public: friend void taskmain(LPVOID param); void
StartTask(); };
void taskmain(LPVOID param) { ExampleTask *
pTaskMain = (ExampleTask *) param; //通過(guò)pTaskMain指針引用 }
void
ExampleTask::StartTask() { _beginthread(taskmain,0,this); } int
main(int argc, char* argv[]) { ExampleTask
realTimeTask; realTimeTask.StartTask(); return
0; } | (3)可以對(duì)非靜態(tài)成員函數(shù)實(shí)現(xiàn)回調(diào),并訪問(wèn)非靜態(tài)成員,此法涉及到一些高級(jí)技巧,在此不再詳述。
2.創(chuàng)建線程
進(jìn)程的主線程由操作系統(tǒng)自動(dòng)生成,Win32提供了CreateThread
API來(lái)完成用戶(hù)線程的創(chuàng)建,該API的原型為:
HANDLE CreateThread( LPSECURITY_ATTRIBUTES lpThreadAttributes,//Pointer
to a SECURITY_ATTRIBUTES structure SIZE_T dwStackSize, //Initial size of the
stack, in bytes. LPTHREAD_START_ROUTINE lpStartAddress, LPVOID
lpParameter, //Pointer to a variable to be passed to the thread DWORD
dwCreationFlags, //Flags that control the creation of the thread LPDWORD
lpThreadId //Pointer to a variable that receives the thread
identifier ); | 如果使用C/C++語(yǔ)言編寫(xiě)多線程應(yīng)用程序,一定不能使用操作系統(tǒng)提供的CreateThread
API,而應(yīng)該使用C/C++運(yùn)行時(shí)庫(kù)中的_beginthread(或_beginthreadex),其函數(shù)原型為:
uintptr_t _beginthread( void( __cdecl *start_address )( void * ),
//Start address of routine that begins execution of new thread unsigned
stack_size, //Stack size for new thread or 0. void *arglist //Argument list
to be passed to new thread or NULL ); uintptr_t _beginthreadex( void
*security,//Pointer to a SECURITY_ATTRIBUTES structure unsigned
stack_size, unsigned ( __stdcall *start_address )( void * ), void
*arglist, unsigned initflag,//Initial state of new thread (0 for running or
CREATE_SUSPENDED for suspended); unsigned *thrdaddr
); | _beginthread函數(shù)與Win32 API
中的CreateThread函數(shù)類(lèi)似,但有如下差異:
(1)通過(guò)_beginthread函數(shù)我們可以利用其參數(shù)列表arglist將多個(gè)參數(shù)傳遞到線程;
?。?)_beginthread 函數(shù)初始化某些 C 運(yùn)行時(shí)庫(kù)變量,在線程中若需要使用 C 運(yùn)行時(shí)庫(kù)。
3.終止線程
線程的終止有如下四種方式:
?。?)線程函數(shù)返回;
(2)線程自身調(diào)用ExitThread
函數(shù)即終止自己,其原型為:
VOID ExitThread(UINT fuExitCode );
| 它將參數(shù)fuExitCode設(shè)置為線程的退出碼。
注意:如果使用C/C++編寫(xiě)代碼,我們應(yīng)該使用C/C++運(yùn)行時(shí)庫(kù)函數(shù)_endthread
(_endthreadex)終止線程,決不能使用ExitThread! _endthread
函數(shù)對(duì)于線程內(nèi)的條件終止很有用。例如,專(zhuān)門(mén)用于通信處理的線程若無(wú)法獲取對(duì)通信端口的控制,則會(huì)退出。
?。?)同一進(jìn)程或其他進(jìn)程的線程調(diào)用TerminateThread函數(shù),其原型為:
BOOL TerminateThread(HANDLE hThread,DWORD dwExitCode);
| 該函數(shù)用來(lái)結(jié)束由hThread參數(shù)指定的線程,并把dwExitCode設(shè)成該線程的退出碼。當(dāng)某個(gè)線程不再響應(yīng)時(shí),我們可以用其他線程調(diào)用該函數(shù)來(lái)終止這個(gè)不響應(yīng)的線程。
?。?)包含線程的進(jìn)程終止。
最好使用第1種方式終止線程,第2~4種方式都不宜采用。
4.掛起與恢復(fù)線程
當(dāng)我們創(chuàng)建線程的時(shí)候,如果給其傳入CREATE_SUSPENDED標(biāo)志,則該線程創(chuàng)建后被掛起,我們應(yīng)使用ResumeThread恢復(fù)它:
DWORD ResumeThread(HANDLE hThread);
| 如果ResumeThread函數(shù)運(yùn)行成功,它將返回線程的前一個(gè)暫停計(jì)數(shù),否則返回0x
FFFFFFFF。
對(duì)于沒(méi)有被掛起的線程,程序員可以調(diào)用SuspendThread函數(shù)強(qiáng)行掛起之:
DWORD SuspendThread(HANDLE
hThread); | 一個(gè)線程可以被掛起多次。線程可以自行暫停運(yùn)行,但是不能自行恢復(fù)運(yùn)行。如果一個(gè)線程被掛起n次,則該線程也必須被恢復(fù)n次才可能得以執(zhí)行。
5.設(shè)置線程優(yōu)先級(jí)
當(dāng)一個(gè)線程被首次創(chuàng)建時(shí),它的優(yōu)先級(jí)等同于它所屬進(jìn)程的優(yōu)先級(jí)。在單個(gè)進(jìn)程內(nèi)可以通過(guò)調(diào)用SetThreadPriority函數(shù)改變線程的相對(duì)優(yōu)先級(jí)。一個(gè)線程的優(yōu)先級(jí)是相對(duì)于其所屬進(jìn)程的優(yōu)先級(jí)而言的。
BOOL SetThreadPriority(HANDLE hThread, int nPriority);
| 其中參數(shù)hThread是指向待修改優(yōu)先級(jí)線程的句柄,線程與包含它的進(jìn)程的優(yōu)先級(jí)關(guān)系如下:
線程優(yōu)先級(jí)
= 進(jìn)程類(lèi)基本優(yōu)先級(jí) +
線程相對(duì)優(yōu)先級(jí)
進(jìn)程類(lèi)的基本優(yōu)先級(jí)包括:
?。?)實(shí)時(shí):REALTIME_PRIORITY_CLASS;
?。?)高:HIGH
_PRIORITY_CLASS;
?。?)高于正常:ABOVE_NORMAL_PRIORITY_CLASS;
(4)正常:NORMAL
_PRIORITY_CLASS;
?。?)低于正常:BELOW_ NORMAL
_PRIORITY_CLASS;
?。?)空閑:IDLE_PRIORITY_CLASS。
我們從Win32任務(wù)管理器中可以直觀的看到這六個(gè)進(jìn)程類(lèi)優(yōu)先級(jí),如下圖:
線程的相對(duì)優(yōu)先級(jí)包括:
?。?)空閑:THREAD_PRIORITY_IDLE;
?。?)最低線程:THREAD_PRIORITY_LOWEST;
?。?)低于正常線程:THREAD_PRIORITY_BELOW_NORMAL;
?。?)正常線程:THREAD_PRIORITY_
NORMAL
(缺省);
?。?)高于正常線程:THREAD_PRIORITY_ABOVE_NORMAL;
?。?)最高線程:THREAD_PRIORITY_HIGHEST;
?。?)關(guān)鍵時(shí)間:THREAD_PRIOTITY_CRITICAL。
下圖給出了進(jìn)程優(yōu)先級(jí)和線程相對(duì)優(yōu)先級(jí)的映射關(guān)系:
例如:
HANDLE hCurrentThread =
GetCurrentThread(); //獲得該線程句柄 SetThreadPriority(hCurrentThread,
THREAD_PRIORITY_LOWEST); | 6.睡眠
VOID Sleep(DWORD
dwMilliseconds); | 該函數(shù)可使線程暫停自己的運(yùn)行,直到dwMilliseconds毫秒過(guò)去為止。它告訴系統(tǒng),自身不想在某個(gè)時(shí)間段內(nèi)被調(diào)度。
7.其它重要API
獲得線程優(yōu)先級(jí)
一個(gè)線程被創(chuàng)建時(shí),就會(huì)有一個(gè)默認(rèn)的優(yōu)先級(jí),但是有時(shí)要?jiǎng)討B(tài)地改變一個(gè)線程的優(yōu)先級(jí),有時(shí)需獲得一個(gè)線程的優(yōu)先級(jí)。
Int GetThreadPriority (HANDLE
hThread); | 如果函數(shù)執(zhí)行發(fā)生錯(cuò)誤,會(huì)返回THREAD_PRIORITY_ERROR_RETURN標(biāo)志。如果函數(shù)成功地執(zhí)行,會(huì)返回優(yōu)先級(jí)標(biāo)志。
獲得線程退出碼
BOOL WINAPI GetExitCodeThread( HANDLE hThread, LPDWORD
lpExitCode ); | 如果執(zhí)行成功,GetExitCodeThread返回TRUE,退出碼被lpExitCode指向內(nèi)存記錄;否則返回FALSE,我們可通過(guò)GetLastError()獲知錯(cuò)誤原因。如果線程尚未結(jié)束,lpExitCode帶回來(lái)的將是STILL_ALIVE。
獲得/設(shè)置線程上下文 BOOL WINAPI GetThreadContext( HANDLE
hThread, LPCONTEXT lpContext ); BOOL WINAPI
SetThreadContext( HANDLE hThread, CONST CONTEXT
*lpContext ); | 由于GetThreadContext和SetThreadContext可以操作CPU內(nèi)部的寄存器,因此在一些高級(jí)技巧的編程中有一定應(yīng)用。譬如,調(diào)試器可利用GetThreadContext掛起被調(diào)試線程獲取其上下文,并設(shè)置上下文中的標(biāo)志寄存器中的陷阱標(biāo)志位,最后通過(guò)SetThreadContext使設(shè)置生效來(lái)進(jìn)行單步調(diào)試。
8.實(shí)例
以下程序使用CreateThread創(chuàng)建兩個(gè)線程,在這兩個(gè)線程中Sleep一段時(shí)間,主線程通過(guò)GetExitCodeThread來(lái)判斷兩個(gè)線程是否結(jié)束運(yùn)行:
#define WIN32_LEAN_AND_MEAN #include <stdio.h> #include
<stdlib.h> #include <windows.h> #include
<conio.h>
DWORD WINAPI ThreadFunc(LPVOID);
int
main() { HANDLE hThrd1; HANDLE hThrd2; DWORD exitCode1 =
0; DWORD exitCode2 = 0; DWORD threadId;
hThrd1 =
CreateThread(NULL, 0, ThreadFunc, (LPVOID)1, 0, &threadId ); if
(hThrd1) printf("Thread 1 launched\n");
hThrd2 = CreateThread(NULL,
0, ThreadFunc, (LPVOID)2, 0, &threadId ); if
(hThrd2) printf("Thread 2 launched\n");
// Keep waiting until both
calls to GetExitCodeThread succeed AND // neither of them returns
STILL_ACTIVE. for (;;) { printf("Press any key to
exit..\n"); getch();
GetExitCodeThread(hThrd1,
&exitCode1); GetExitCodeThread(hThrd2, &exitCode2); if (
exitCode1 == STILL_ACTIVE ) puts("Thread 1 is still running!"); if (
exitCode2 == STILL_ACTIVE ) puts("Thread 2 is still running!"); if (
exitCode1 != STILL_ACTIVE && exitCode2 != STILL_ACTIVE
) break; }
CloseHandle(hThrd1); CloseHandle(hThrd2);
printf("Thread
1 returned %d\n", exitCode1); printf("Thread 2 returned %d\n",
exitCode2);
return EXIT_SUCCESS; }
/* * Take the startup
value, do some simple math on it, * and return the calculated
value. */ DWORD WINAPI ThreadFunc(LPVOID
n) { Sleep((DWORD)n*1000*2); return (DWORD)n *
10; } | 通過(guò)下面的程序我們可以看出多線程程序運(yùn)行順序的難以預(yù)料以及WINAPI的CreateThread函數(shù)與C運(yùn)行時(shí)庫(kù)的_beginthread的差別:
#define WIN32_LEAN_AND_MEAN #include <stdio.h> #include
<stdlib.h> #include <windows.h>
DWORD WINAPI
ThreadFunc(LPVOID);
int main() { HANDLE hThrd; DWORD
threadId; int i;
for (i = 0; i < 5; i++) { hThrd =
CreateThread(NULL, 0, ThreadFunc, (LPVOID)i, 0, &threadId); if
(hThrd) { printf("Thread launched %d\n",
i); CloseHandle(hThrd); } } // Wait for the threads to
complete. Sleep(2000);
return EXIT_SUCCESS; }
DWORD WINAPI
ThreadFunc(LPVOID n) { int i; for (i = 0; i < 10;
i++) printf("%d%d%d%d%d%d%d%d\n", n, n, n, n, n, n, n, n); return
0; } | 運(yùn)行的輸出具有很大的隨機(jī)性,這里摘取了幾次結(jié)果的一部分(幾乎每一次都不同):
如果我們使用標(biāo)準(zhǔn)C庫(kù)函數(shù)而不是多線程版的運(yùn)行時(shí)庫(kù),則程序可能輸出"3333444444"這樣的結(jié)果,而使用多線程運(yùn)行時(shí)庫(kù)后,則可避免這一問(wèn)題。
下列程序在主線程中創(chuàng)建一個(gè)SecondThread,在SecondThread線程中通過(guò)自增對(duì)Counter計(jì)數(shù)到1000000,主線程一直等待其結(jié)束:
#include <Win32.h> #include <stdio.h> #include
<process.h>
unsigned Counter; unsigned __stdcall
SecondThreadFunc(void *pArguments) { printf("In second
thread...\n");
while (Counter <
1000000) Counter++;
_endthreadex(0); return 0; }
int
main() { HANDLE hThread; unsigned threadID;
printf("Creating
second thread...\n");
// Create the second thread. hThread =
(HANDLE)_beginthreadex(NULL, 0, &SecondThreadFunc, NULL, 0,
&threadID);
// Wait until second thread terminates
WaitForSingleObject(hThread, INFINITE); printf("Counter should be
1000000; it is-> %d\n", Counter); // Destroy the thread
object. CloseHandle(hThread); }
| 深入淺出Win32多線程程序設(shè)計(jì)之線程通信 簡(jiǎn)介 線程之間通信的兩個(gè)基本問(wèn)題是互斥和同步。 線程同步是指線程之間所具有的一種制約關(guān)系,一個(gè)線程的執(zhí)行依賴(lài)另一個(gè)線程的消息,當(dāng)它沒(méi)有得到另一個(gè)線程的消息時(shí)應(yīng)等待,直到消息到達(dá)時(shí)才被喚醒。 線程互斥是指對(duì)于共享的操作系統(tǒng)資源(指的是廣義的"資源",而不是Windows的.res文件,譬如全局變量就是一種共享資源),在各線程訪問(wèn)時(shí)的排它性。當(dāng)有若干個(gè)線程都要使用某一共享資源時(shí),任何時(shí)刻最多只允許一個(gè)線程去使用,其它要使用該資源的線程必須等待,直到占用資源者釋放該資源。 線程互斥是一種特殊的線程同步。 實(shí)際上,互斥和同步對(duì)應(yīng)著線程間通信發(fā)生的兩種情況: ?。?)當(dāng)有多個(gè)線程訪問(wèn)共享資源而不使資源被破壞時(shí); (2)當(dāng)一個(gè)線程需要將某個(gè)任務(wù)已經(jīng)完成的情況通知另外一個(gè)或多個(gè)線程時(shí)。 在WIN32中,同步機(jī)制主要有以下幾種: (1)事件(Event); ?。?)信號(hào)量(semaphore); ?。?)互斥量(mutex); (4)臨界區(qū)(Critical
section)。 全局變量 因?yàn)檫M(jìn)程中的所有線程均可以訪問(wèn)所有的全局變量,因而全局變量成為Win32多線程通信的最簡(jiǎn)單方式。例如:
int var; //全局變量 UINT ThreadFunction(LPVOIDpParam) { var =
0; while (var <
MaxValue) { //線程處理 ::InterlockedIncrement(long*)
&var); } return 0; } 請(qǐng)看下列程序: int globalFlag = false;
DWORD WINAPI ThreadFunc(LPVOID n) { Sleep(2000); globalFlag =
true;
return 0; }
int main() { HANDLE hThrd; DWORD
threadId;
hThrd = CreateThread(NULL, 0, ThreadFunc, NULL, 0,
&threadId); if (hThrd) { printf("Thread
launched\n"); CloseHandle(hThrd); }
while
(!globalFlag) ; printf("exit\n"); } | 上述程序中使用全局變量和while循環(huán)查詢(xún)進(jìn)行線程間同步,實(shí)際上,這是一種應(yīng)該避免的方法,因?yàn)椋?
(1)當(dāng)主線程必須使自己與ThreadFunc函數(shù)的完成運(yùn)行實(shí)現(xiàn)同步時(shí),它并沒(méi)有使自己進(jìn)入睡眠狀態(tài)。由于主線程沒(méi)有進(jìn)入睡眠狀態(tài),因此操作系統(tǒng)繼續(xù)為它調(diào)度C
P
U時(shí)間,這就要占用其他線程的寶貴時(shí)間周期; ?。?)當(dāng)主線程的優(yōu)先級(jí)高于執(zhí)行ThreadFunc函數(shù)的線程時(shí),就會(huì)發(fā)生globalFlag永遠(yuǎn)不能被賦值為true的情況。因?yàn)樵谶@種情況下,系統(tǒng)決不會(huì)將任何時(shí)間片分配給ThreadFunc線程。 事件 事件(Event)是WIN32提供的最靈活的線程間同步方式,事件可以處于激發(fā)狀態(tài)(signaled
or true)或未激發(fā)狀態(tài)(unsignal or
false)。根據(jù)狀態(tài)變遷方式的不同,事件可分為兩類(lèi): ?。?)手動(dòng)設(shè)置:這種對(duì)象只可能用程序手動(dòng)設(shè)置,在需要該事件或者事件發(fā)生時(shí),采用SetEvent及ResetEvent來(lái)進(jìn)行設(shè)置。 (2)自動(dòng)恢復(fù):一旦事件發(fā)生并被處理后,自動(dòng)恢復(fù)到?jīng)]有事件狀態(tài),不需要再次設(shè)置。 創(chuàng)建事件的函數(shù)原型為:
HANDLE CreateEvent( LPSECURITY_ATTRIBUTES lpEventAttributes, //
SECURITY_ATTRIBUTES結(jié)構(gòu)指針,可為NULL BOOL bManualReset, // 手動(dòng)/自動(dòng) //
TRUE:在WaitForSingleObject后必須手動(dòng)調(diào)用ResetEvent清除信號(hào) //
FALSE:在WaitForSingleObject后,系統(tǒng)自動(dòng)清除事件信號(hào) BOOL bInitialState,
//初始狀態(tài) LPCTSTR lpName
//事件的名稱(chēng) ); | 使用"事件"機(jī)制應(yīng)注意以下事項(xiàng): ?。?)如果跨進(jìn)程訪問(wèn)事件,必須對(duì)事件命名,在對(duì)事件命名的時(shí)候,要注意不要與系統(tǒng)命名空間中的其它全局命名對(duì)象沖突; ?。?)事件是否要自動(dòng)恢復(fù); ?。?)事件的初始狀態(tài)設(shè)置。 由于event對(duì)象屬于內(nèi)核對(duì)象,故進(jìn)程B可以調(diào)用OpenEvent函數(shù)通過(guò)對(duì)象的名字獲得進(jìn)程A中event對(duì)象的句柄,然后將這個(gè)句柄用于ResetEvent、SetEvent和WaitForMultipleObjects等函數(shù)中。此法可以實(shí)現(xiàn)一個(gè)進(jìn)程的線程控制另一進(jìn)程中線程的運(yùn)行,例如:
HANDLE hEvent=OpenEvent(EVENT_ALL_ACCESS,true,"MyEvent");
ResetEvent(hEvent); | 臨界區(qū) 定義臨界區(qū)變量
CRITICAL_SECTION
gCriticalSection; | 通常情況下,CRITICAL_SECTION結(jié)構(gòu)體應(yīng)該被定義為全局變量,以便于進(jìn)程中的所有線程方便地按照變量名來(lái)引用該結(jié)構(gòu)體。 初始化臨界區(qū)
VOID WINAPI InitializeCriticalSection( LPCRITICAL_SECTION
lpCriticalSection //指向程序員定義的CRITICAL_SECTION變量 ); | 該函數(shù)用于對(duì)pcs所指的CRITICAL_SECTION結(jié)構(gòu)體進(jìn)行初始化。該函數(shù)只是設(shè)置了一些成員變量,它的運(yùn)行一般不會(huì)失敗,因此它采用了VOID類(lèi)型的返回值。該函數(shù)必須在任何線程調(diào)用EnterCriticalSection函數(shù)之前被調(diào)用,如果一個(gè)線程試圖進(jìn)入一個(gè)未初始化的CRTICAL_SECTION,那么結(jié)果將是很難預(yù)計(jì)的。 刪除臨界區(qū)
VOID WINAPI DeleteCriticalSection( LPCRITICAL_SECTION
lpCriticalSection //指向一個(gè)不再需要的CRITICAL_SECTION變量 ); | 進(jìn)入臨界區(qū)
VOID WINAPI EnterCriticalSection( LPCRITICAL_SECTION
lpCriticalSection //指向一個(gè)你即將鎖定的CRITICAL_SECTION變量 ); | 離開(kāi)臨界區(qū)
VOID WINAPI LeaveCriticalSection( LPCRITICAL_SECTION
lpCriticalSection //指向一個(gè)你即將離開(kāi)的CRITICAL_SECTION變量 ); | 使用臨界區(qū)編程的一般方法是:
void
UpdateData() { EnterCriticalSection(&gCriticalSection); ...//do
something LeaveCriticalSection(&gCriticalSection); } | 關(guān)于臨界區(qū)的使用,有下列注意點(diǎn): ?。?)每個(gè)共享資源使用一個(gè)CRITICAL_SECTION變量; ?。?)不要長(zhǎng)時(shí)間運(yùn)行關(guān)鍵代碼段,當(dāng)一個(gè)關(guān)鍵代碼段長(zhǎng)時(shí)間運(yùn)行時(shí),其他線程就會(huì)進(jìn)入等待狀態(tài),這會(huì)降低應(yīng)用程序的運(yùn)行性能; (3)如果需要同時(shí)訪問(wèn)多個(gè)資源,則可能連續(xù)調(diào)用EnterCriticalSection; ?。?)Critical
Section不是OS核心對(duì)象,如果進(jìn)入臨界區(qū)的線程"掛"了,將無(wú)法釋放臨界資源。這個(gè)缺點(diǎn)在Mutex中得到了彌補(bǔ)。 互斥 互斥量的作用是保證每次只能有一個(gè)線程獲得互斥量而得以繼續(xù)執(zhí)行,使用CreateMutex函數(shù)創(chuàng)建:
HANDLE CreateMutex( LPSECURITY_ATTRIBUTES lpMutexAttributes, //
安全屬性結(jié)構(gòu)指針,可為NULL BOOL bInitialOwner,
//是否占有該互斥量,TRUE:占有,F(xiàn)ALSE:不占有 LPCTSTR lpName
//信號(hào)量的名稱(chēng) );
| Mutex是核心對(duì)象,可以跨進(jìn)程訪問(wèn),下面的代碼給出了從另一進(jìn)程訪問(wèn)命名Mutex的例子:
HANDLE hMutex; hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, L"mutexName");
if (hMutex){ …
} else{ … } | 相關(guān)API:
BOOL WINAPI ReleaseMutex( HANDLE
hMutex ); | 使用互斥編程的一般方法是:
void UpdateResource() { WaitForSingleObject(hMutex,…); ...//do
something ReleaseMutex(hMutex); } | 互斥(mutex)內(nèi)核對(duì)象能夠確保線程擁有對(duì)單個(gè)資源的互斥訪問(wèn)權(quán)?;コ鈱?duì)象的行為特性與臨界區(qū)相同,但是互斥對(duì)象屬于內(nèi)核對(duì)象,而臨界區(qū)則屬于用戶(hù)方式對(duì)象,因此這導(dǎo)致mutex與Critical
Section的如下不同: ?。?) 互斥對(duì)象的運(yùn)行速度比關(guān)鍵代碼段要慢; ?。?)
不同進(jìn)程中的多個(gè)線程能夠訪問(wèn)單個(gè)互斥對(duì)象; (3)
線程在等待訪問(wèn)資源時(shí)可以設(shè)定一個(gè)超時(shí)值。 下圖更詳細(xì)地列出了互斥與臨界區(qū)的不同:
 信號(hào)量
信號(hào)量是維護(hù)0到指定最大值之間的同步對(duì)象。信號(hào)量狀態(tài)在其計(jì)數(shù)大于0時(shí)是有信號(hào)的,而其計(jì)數(shù)是0時(shí)是無(wú)信號(hào)的。信號(hào)量對(duì)象在控制上可以支持有限數(shù)量共享資源的訪問(wèn)。
信號(hào)量的特點(diǎn)和用途可用下列幾句話定義:
?。?)如果當(dāng)前資源的數(shù)量大于0,則信號(hào)量有效;
?。?)如果當(dāng)前資源數(shù)量是0,則信號(hào)量無(wú)效;
?。?)系統(tǒng)決不允許當(dāng)前資源的數(shù)量為負(fù)值;
?。?)當(dāng)前資源數(shù)量決不能大于最大資源數(shù)量。
創(chuàng)建信號(hào)量
HANDLE CreateSemaphore ( PSECURITY_ATTRIBUTE psa, LONG
lInitialCount, //開(kāi)始時(shí)可供使用的資源數(shù) LONG lMaximumCount, //最大資源數(shù) PCTSTR
pszName); |
釋放信號(hào)量
通過(guò)調(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 ); |
打開(kāi)信號(hào)量
和其他核心對(duì)象一樣,信號(hào)量也可以通過(guò)名字跨進(jìn)程訪問(wèn),打開(kāi)信號(hào)量的API為:
HANDLE OpenSemaphore ( DWORD fdwAccess, BOOL
bInherithandle, PCTSTR
pszName ); |
互鎖訪問(wèn)
當(dāng)必須以原子操作方式來(lái)修改單個(gè)值時(shí),互鎖訪問(wèn)函數(shù)是相當(dāng)有用的。所謂原子訪問(wèn),是指線程在訪問(wèn)資源時(shí)能夠確保所有其他線程都不在同一時(shí)間內(nèi)訪問(wèn)相同的資源。
請(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è)問(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保證對(duì)變量globalVar的訪問(wèn)具有"原子性"?;ユi訪問(wèn)的控制速度非???,調(diào)用一個(gè)互鎖函數(shù)的CPU周期通常小于50,不需要進(jìn)行用戶(hù)方式與內(nèi)核方式的切換(該切換通常需要運(yùn)行1000個(gè)CPU周期)。
互鎖訪問(wèn)函數(shù)的缺點(diǎn)在于其只能對(duì)單一變量進(jìn)行原子訪問(wèn),如果要訪問(wèn)的資源比較復(fù)雜,仍要使用臨界區(qū)或互斥。
可等待定時(shí)器
可等待定時(shí)器是在某個(gè)時(shí)間或按規(guī)定的間隔時(shí)間發(fā)出自己的信號(hào)通知的內(nèi)核對(duì)象。它們通常用來(lái)在某個(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ù)來(lái)界定定時(shí)器在何時(shí)被激活:
BOOL SetWaitableTimer( HANDLE hTimer, //要設(shè)置的定時(shí)器 const LARGE_INTEGER
*pDueTime, //指明定時(shí)器第一次激活的時(shí)間 LONG lPeriod,
//指明此后定時(shí)器應(yīng)該間隔多長(zhǎng)時(shí)間激活一次 PTIMERAPCROUTINE pfnCompletionRoutine, PVOID
PvArgToCompletionRoutine, BOOL
fResume); |
取消可等待定時(shí)器
BOOl Cancel WaitableTimer( HANDLE hTimer
//要取消的定時(shí)器 ); |
打開(kāi)可等待定時(shí)器
作為一種內(nèi)核對(duì)象,WaitableTimer也可以被其他進(jìn)程以名字打開(kāi):
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)工作者線程和用戶(hù)接口(UI)線程。 工作者線程
CWinThread *AfxBeginThread( AFX_THREADPROC pfnThreadProc,
//控制函數(shù) LPVOID pParam, //傳遞給控制函數(shù)的參數(shù) int nPriority =
THREAD_PRIORITY_NORMAL, //線程的優(yōu)先級(jí) UINT nStackSize = 0, //線程的堆棧大小 DWORD
dwCreateFlags = 0, //線程的創(chuàng)建標(biāo)志 LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL
//線程的安全屬性 ); | 工作者線程編程較為簡(jiǎn)單,只需編寫(xiě)線程控制函數(shù)和啟動(dòng)線程即可。下面的代碼給出了定義一個(gè)控制函數(shù)和啟動(dòng)它的過(guò)程:
//線程控制函數(shù) UINT MfcThreadProc(LPVOID lpParam) { CExampleClass
*lpObject = (CExampleClass*)lpParam; if (lpObject == NULL ||
!lpObject->IsKindof(RUNTIME_CLASS(CExampleClass))) return - 1; //輸入?yún)?shù)非法
//線程成功啟動(dòng) while (1) { ...// } return
0; }
//在MFC程序中啟動(dòng)線程 AfxBeginThread(MfcThreadProc,
lpObject); | UI線程 創(chuàng)建用戶(hù)界面線程時(shí),必須首先從CWinThread
派生類(lèi),并使用 DECLARE_DYNCREATE 和 IMPLEMENT_DYNCREATE
宏聲明此類(lèi)。 下面給出了CWinThread類(lèi)的原型(添加了關(guān)于其重要函數(shù)功能和是否需要被繼承類(lèi)重載的注釋?zhuān)?br>
class CWinThread : public
CCmdTarget { DECLARE_DYNAMIC(CWinThread)
public: //
Constructors CWinThread(); BOOL CreateThread(DWORD dwCreateFlags = 0,
UINT nStackSize = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs =
NULL);
// Attributes CWnd* m_pMainWnd; // main window (usually
same AfxGetApp()->m_pMainWnd) CWnd* m_pActiveWnd; // active main window
(may not be m_pMainWnd) BOOL m_bAutoDelete; // enables 'delete this' after
thread termination
// only valid while running HANDLE m_hThread;
// this thread's HANDLE operator HANDLE() const; DWORD m_nThreadID; //
this thread's ID
int GetThreadPriority(); BOOL
SetThreadPriority(int nPriority);
// Operations DWORD
SuspendThread(); DWORD ResumeThread(); BOOL PostThreadMessage(UINT
message, WPARAM wParam, LPARAM lParam);
//
Overridables //執(zhí)行線程實(shí)例初始化,必須重寫(xiě) virtual BOOL InitInstance();
//
running and idle processing //控制線程的函數(shù),包含消息泵,一般不重寫(xiě) virtual int
Run();
//消息調(diào)度到TranslateMessage和DispatchMessage之前對(duì)其進(jìn)行篩選, //通常不重寫(xiě) virtual
BOOL PreTranslateMessage(MSG* pMsg);
virtual BOOL PumpMessage(); // low
level message pump
//執(zhí)行線程特定的閑置時(shí)間處理,通常不重寫(xiě) virtual BOOL OnIdle(LONG
lCount); // return TRUE if more idle processing virtual BOOL
IsIdleMessage(MSG* pMsg); // checks for special
messages
//線程終止時(shí)執(zhí)行清除,通常需要重寫(xiě) virtual int ExitInstance(); // default
will 'delete this'
//截獲由線程的消息和命令處理程序引發(fā)的未處理異常,通常不重寫(xiě) virtual LRESULT
ProcessWndProcException(CException* e, const MSG* pMsg);
// Advanced:
handling messages sent to message filter hook virtual BOOL
ProcessMessageFilter(int code, LPMSG lpMsg);
// Advanced: virtual
access to m_pMainWnd virtual CWnd* GetMainWnd();
//
Implementation public: virtual ~CWinThread(); #ifdef
_DEBUG virtual void AssertValid() const; virtual void
Dump(CDumpContext& dc) const; int m_nDisablePumpCount; // Diagnostic
trap to detect illegal re-entrancy #endif void
CommonConstruct(); virtual void Delete(); // 'delete this' only if
m_bAutoDelete == TRUE
// message pump for Run MSG m_msgCur; //
current message
public: // constructor used by implementation of
AfxBeginThread CWinThread(AFX_THREADPROC pfnThreadProc, LPVOID
pParam);
// valid after construction LPVOID m_pThreadParams; //
generic parameters passed to starting function AFX_THREADPROC
m_pfnThreadProc;
// set after OLE is initialized void (AFXAPI*
m_lpfnOleTermOrFreeLib)(BOOL, BOOL); COleMessageFilter*
m_pMessageFilter;
protected: CPoint m_ptCursorLast; // last mouse
position UINT m_nMsgLast; // last mouse message BOOL
DispatchThreadMessageEx(MSG* msg); // helper void
DispatchThreadMessage(MSG* msg); //
obsolete };
| 啟動(dòng)UI線程的AfxBeginThread函數(shù)的原型為:
CWinThread *AfxBeginThread( //從CWinThread派生的類(lèi)的
RUNTIME_CLASS CRuntimeClass *pThreadClass, int nPriority =
THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags =
0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL );
| 我們可以方便地使用VC++
6.0類(lèi)向?qū)Фx一個(gè)繼承自CWinThread的用戶(hù)線程類(lèi)。下面給出產(chǎn)生我們自定義的CWinThread子類(lèi)CMyUIThread的方法。 打開(kāi)VC++
6.0類(lèi)向?qū)В谌缦麓翱谥羞x擇Base
Class類(lèi)為CWinThread,輸入子類(lèi)名為CMyUIThread,點(diǎn)擊"OK"按鈕后就產(chǎn)生了類(lèi)CMyUIThread。
其源代碼框架為:
///////////////////////////////////////////////////////////////////////////// //
CMyUIThread thread
class CMyUIThread : public
CWinThread { DECLARE_DYNCREATE(CMyUIThread) protected: CMyUIThread();
// protected constructor used by dynamic creation
//
Attributes public:
// Operations public:
//
Overrides // ClassWizard generated virtual function
overrides //{{AFX_VIRTUAL(CMyUIThread) public: virtual BOOL
InitInstance(); virtual int
ExitInstance(); //}}AFX_VIRTUAL
//
Implementation protected: virtual ~CMyUIThread();
// Generated
message map functions //{{AFX_MSG(CMyUIThread) // NOTE - the
ClassWizard will add and remove member functions
here. //}}AFX_MSG
DECLARE_MESSAGE_MAP() };
///////////////////////////////////////////////////////////////////////////// //
CMyUIThread
IMPLEMENT_DYNCREATE(CMyUIThread,
CWinThread)
CMyUIThread::CMyUIThread() {}
CMyUIThread::~CMyUIThread() {}
BOOL
CMyUIThread::InitInstance() { // TODO: perform and per-thread
initialization here return TRUE; }
int
CMyUIThread::ExitInstance() { // TODO: perform any per-thread cleanup
here return
CWinThread::ExitInstance(); }
BEGIN_MESSAGE_MAP(CMyUIThread,
CWinThread) //{{AFX_MSG_MAP(CMyUIThread) // NOTE - the ClassWizard will
add and remove mapping macros
here. //}}AFX_MSG_MAP END_MESSAGE_MAP() | 使用下列代碼就可以啟動(dòng)這個(gè)UI線程:
CMyUIThread *pThread; pThread = (CMyUIThread*) AfxBeginThread(
RUNTIME_CLASS(CMyUIThread)
); | 另外,我們也可以不用AfxBeginThread
創(chuàng)建線程,而是分如下兩步完成: ?。?)調(diào)用線程類(lèi)的構(gòu)造函數(shù)創(chuàng)建一個(gè)線程對(duì)象; (2)調(diào)用CWinThread::CreateThread函數(shù)來(lái)啟動(dòng)該線程。 在線程自身內(nèi)調(diào)用AfxEndThread函數(shù)可以終止該線程:
void AfxEndThread( UINT nExitCode //the exit code of the
thread ); | 對(duì)于UI線程而言,如果消息隊(duì)列中放入了WM_QUIT消息,將結(jié)束線程。 關(guān)于UI線程和工作者線程的分配,最好的做法是:將所有與UI相關(guān)的操作放入主線程,其它的純粹的運(yùn)算工作交給獨(dú)立的數(shù)個(gè)工作者線程。 候捷先生早些時(shí)間喜歡為MDI程序的每個(gè)窗口創(chuàng)建一個(gè)線程,他后來(lái)澄清了這個(gè)錯(cuò)誤。因?yàn)槿绻麨镸DI程序的每個(gè)窗口都單獨(dú)創(chuàng)建一個(gè)線程,在窗口進(jìn)行切換的時(shí)候,將進(jìn)行線程的上下文切換! 2.線程間通信 MFC中定義了繼承自CSyncObject類(lèi)的CCriticalSection
、CCEvent、CMutex、CSemaphore類(lèi)封裝和簡(jiǎn)化了WIN32
API所提供的臨界區(qū)、事件、互斥和信號(hào)量。使用這些同步機(jī)制,必須包含"Afxmt.h"頭文件。下圖給出了類(lèi)的繼承關(guān)系:
作為CSyncObject類(lèi)的繼承類(lèi),我們僅僅使用基類(lèi)CSyncObject的接口函數(shù)就可以方便、統(tǒng)一的操作CCriticalSection
、CCEvent、CMutex、CSemaphore類(lèi),下面是CSyncObject類(lèi)的原型:
class CSyncObject : public
CObject { DECLARE_DYNAMIC(CSyncObject)
//
Constructor public: CSyncObject(LPCTSTR pstrName);
//
Attributes public: operator HANDLE() const; HANDLE
m_hObject;
// Operations virtual BOOL Lock(DWORD dwTimeout =
INFINITE); virtual BOOL Unlock() = 0; virtual BOOL Unlock(LONG /*
lCount */, LPLONG /* lpPrevCount=NULL */) { return TRUE; }
//
Implementation public: virtual ~CSyncObject(); #ifdef
_DEBUG CString m_strName; virtual void AssertValid()
const; virtual void Dump(CDumpContext& dc)
const; #endif friend class CSingleLock; friend class
CMultiLock; }; | CSyncObject類(lèi)最主要的兩個(gè)函數(shù)是Lock和Unlock,若我們直接使用CSyncObject類(lèi)及其派生類(lèi),我們需要非常小心地在Lock之后調(diào)用Unlock。 MFC提供的另兩個(gè)類(lèi)CSingleLock(等待一個(gè)對(duì)象)和CMultiLock(等待多個(gè)對(duì)象)為我們編寫(xiě)應(yīng)用程序提供了更靈活的機(jī)制,下面以實(shí)際來(lái)闡述CSingleLock的用法:
class
CThreadSafeWnd { public: CThreadSafeWnd(){} ~CThreadSafeWnd(){} void
SetWindow(CWnd *pwnd) { m_pCWnd = pwnd; } void
PaintBall(COLORREF color, CRect &rc); private: CWnd
*m_pCWnd; CCriticalSection m_CSect; };
void
CThreadSafeWnd::PaintBall(COLORREF color, CRect &rc) { CSingleLock
csl(&m_CSect); //缺省的Timeout是INFINITE,只有m_Csect被激活,csl.Lock()才能返回 //true,這里一直等待 if
(csl.Lock()) ; { // not
necessary //AFX_MANAGE_STATE(AfxGetStaticModuleState( )); CDC *pdc =
m_pCWnd->GetDC(); CBrush brush(color); CBrush *oldbrush =
pdc->SelectObject(&brush); pdc->Ellipse(rc); pdc->SelectObject(oldbrush); GdiFlush();
// don't wait to update the
display } } | 上述實(shí)例講述了用CSingleLock對(duì)Windows
GDI相關(guān)對(duì)象進(jìn)行保護(hù)的方法,下面再給出一個(gè)其他方面的例子:
int array1[10], array2[10]; CMutexSection section;
//創(chuàng)建一個(gè)CMutex類(lèi)的對(duì)象
//賦值線程控制函數(shù) UINT EvaluateThread(LPVOID param)
{ CSingleLock singlelock;
singlelock(§ion);
//互斥區(qū)域 singlelock.Lock(); for
(int i = 0; i < 10; i++) array1[i] =
i; singlelock.Unlock(); } //拷貝線程控制函數(shù) UINT CopyThread(LPVOID param)
{ CSingleLock
singlelock; singlelock(§ion);
//互斥區(qū)域 singlelock.Lock(); for
(int i = 0; i < 10; i++) array2[i] =
array1[i]; singlelock.Unlock(); } }
AfxBeginThread(EvaluateThread,
NULL); //啟動(dòng)賦值線程 AfxBeginThread(CopyThread, NULL);
//啟動(dòng)拷貝線程 | 上面的例子中啟動(dòng)了兩個(gè)線程EvaluateThread和CopyThread,線程EvaluateThread把10個(gè)數(shù)賦值給數(shù)組array1[],線程CopyThread將數(shù)組array1[]拷貝給數(shù)組array2[]。由于數(shù)組的拷貝和賦值都是整體行為,如果不以互斥形式執(zhí)行代碼段:
for (int i = 0; i < 10; i++) array1[i] =
i; | 和
for (int i = 0; i < 10; i++) array2[i] =
array1[i]; | 其結(jié)果是很難預(yù)料的! 除了可使用CCriticalSection、CEvent、CMutex、CSemaphore作為線程間同步通信的方式以外,我們還可以利用PostThreadMessage函數(shù)在線程間發(fā)送消息:
BOOL PostThreadMessage(DWORD idThread, // thread identifier UINT Msg, //
message to post WPARAM wParam, // first message parameter LPARAM lParam //
second message parameter ); | 3.線程與消息隊(duì)列 在WIN32中,每一個(gè)線程都對(duì)應(yīng)著一個(gè)消息隊(duì)列。由于一個(gè)線程可以產(chǎn)生數(shù)個(gè)窗口,所以并不是每個(gè)窗口都對(duì)應(yīng)著一個(gè)消息隊(duì)列。下列幾句話應(yīng)該作為"定理"被記?。?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ì)列處理的過(guò)程將有助于我們進(jìn)一步理解UI線程與消息隊(duì)列的關(guān)系,為此我們需要簡(jiǎn)單地?cái)⑹鲆幌翸FC程序的"生死因果"(侯捷:《深入淺出MFC》)。 使用VC++
6.0的向?qū)瓿梢粋€(gè)最簡(jiǎn)單的單文檔架構(gòu)MFC應(yīng)用程序MFCThread: (1) 輸入MFC
EXE工程名MFCThread; ?。?) 選擇單文檔架構(gòu),不支持Document/View結(jié)構(gòu); (3)
ActiveX、3D
container等其他選項(xiàng)都選擇無(wú)。 我們來(lái)分析這個(gè)工程。下面是產(chǎn)生的核心源代碼: MFCThread.h
文件
class CMFCThreadApp : public
CWinApp { public: CMFCThreadApp();
// Overrides //
ClassWizard generated virtual function
overrides //{{AFX_VIRTUAL(CMFCThreadApp) public: virtual BOOL
InitInstance(); //}}AFX_VIRTUAL
//
Implementation
public: //{{AFX_MSG(CMFCThreadApp) afx_msg
void OnAppAbout(); // NOTE - the ClassWizard will add and remove member
functions here. // DO NOT EDIT what you see in these blocks of generated
code
! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; | MFCThread.cpp文件
CMFCThreadApp
theApp;
///////////////////////////////////////////////////////////////////////////// //
CMFCThreadApp initialization
BOOL
CMFCThreadApp::InitInstance() { … CMainFrame* pFrame = new
CMainFrame; m_pMainWnd = pFrame;
// create and load the frame with
its resources pFrame->LoadFrame(IDR_MAINFRAME,WS_OVERLAPPEDWINDOW |
FWS_ADDTOTITLE, NULL,NULL); // The one and only window has been initialized,
so show and update
it. pFrame->ShowWindow(SW_SHOW); pFrame->UpdateWindow();
return
TRUE; } | MainFrm.h文件
#include "ChildView.h"
class CMainFrame : public
CFrameWnd { public: CMainFrame(); protected:
DECLARE_DYNAMIC(CMainFrame)
// Attributes public:
//
Operations public: // Overrides // ClassWizard generated virtual
function overrides //{{AFX_VIRTUAL(CMainFrame) virtual BOOL
PreCreateWindow(CREATESTRUCT& cs); virtual BOOL OnCmdMsg(UINT nID, int
nCode, void* pExtra, AFX_CMDHANDLERINFO*
pHandlerInfo); //}}AFX_VIRTUAL
//
Implementation public: virtual ~CMainFrame(); #ifdef
_DEBUG virtual void AssertValid() const; virtual void
Dump(CDumpContext& dc) const; #endif CChildView
m_wndView;
// Generated message map
functions protected: //{{AFX_MSG(CMainFrame) afx_msg void
OnSetFocus(CWnd *pOldWnd); // NOTE - the ClassWizard will add and remove
member functions here. // DO NOT EDIT what you see in these blocks of
generated
code! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; | MainFrm.cpp文件
IMPLEMENT_DYNAMIC(CMainFrame,
CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame,
CFrameWnd) //{{AFX_MSG_MAP(CMainFrame) // NOTE - the ClassWizard will
add and remove mapping macros here. // DO NOT EDIT what you see in these
blocks of generated code
! ON_WM_SETFOCUS() //}}AFX_MSG_MAP END_MESSAGE_MAP()
///////////////////////////////////////////////////////////////////////////// //
CMainFrame construction/destruction
CMainFrame::CMainFrame() { //
TODO: add member initialization code
here }
CMainFrame::~CMainFrame() {}
BOOL
CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if(
!CFrameWnd::PreCreateWindow(cs) ) return FALSE; // TODO: Modify the
Window class or styles here by modifying // the CREATESTRUCT
cs
cs.dwExStyle &= ~WS_EX_CLIENTEDGE; cs.lpszClass =
AfxRegisterWndClass(0); return
TRUE; } | ChildView.h文件
// CChildView window
class CChildView : public CWnd { //
Construction public: CChildView();
//
Attributes public: // Operations public: // Overrides //
ClassWizard generated virtual function
overrides //{{AFX_VIRTUAL(CChildView) protected: virtual BOOL
PreCreateWindow(CREATESTRUCT& cs); //}}AFX_VIRTUAL
//
Implementation public: virtual ~CChildView();
// Generated
message map functions protected: //{{AFX_MSG(CChildView) afx_msg
void
OnPaint(); //}}AFX_MSG DECLARE_MESSAGE_MAP() };
ChildView.cpp文件 //
CChildView
CChildView::CChildView() {}
CChildView::~CChildView() {}
BEGIN_MESSAGE_MAP(CChildView,CWnd
) //{{AFX_MSG_MAP(CChildView) ON_WM_PAINT() //}}AFX_MSG_MAP END_MESSAGE_MAP()
///////////////////////////////////////////////////////////////////////////// //
CChildView message handlers
BOOL
CChildView::PreCreateWindow(CREATESTRUCT& cs) { if
(!CWnd::PreCreateWindow(cs)) return FALSE;
cs.dwExStyle |=
WS_EX_CLIENTEDGE; cs.style &= ~WS_BORDER; cs.lpszClass =
AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS,::LoadCursor(NULL,
IDC_ARROW), HBRUSH(COLOR_WINDOW+1),NULL);
return
TRUE; }
void CChildView::OnPaint() { CPaintDC dc(this); //
device context for painting
// TODO: Add your message handler code
here // Do not call CWnd::OnPaint() for painting
messages } | 文件MFCThread.h和MFCThread.cpp定義和實(shí)現(xiàn)的類(lèi)CMFCThreadApp繼承自CWinApp類(lèi),而CWinApp類(lèi)又繼承自CWinThread類(lèi)(CWinThread類(lèi)又繼承自CCmdTarget類(lèi)),所以CMFCThread本質(zhì)上是一個(gè)MFC線程類(lèi),下圖給出了相關(guān)的類(lèi)層次結(jié)構(gòu):
 我們提取CWinApp類(lèi)原型的一部分:
class CWinApp : public
CWinThread { DECLARE_DYNAMIC(CWinApp) public: //
Constructor CWinApp(LPCTSTR lpszAppName = NULL);// default app name //
Attributes // Startup args (do not change) HINSTANCE
m_hInstance; HINSTANCE m_hPrevInstance; LPTSTR m_lpCmdLine; int
m_nCmdShow; // Running args (can be changed in InitInstance) LPCTSTR
m_pszAppName; // human readable name LPCTSTR m_pszExeName; // executable
name (no spaces) LPCTSTR m_pszHelpFilePath; // default based on module
path LPCTSTR m_pszProfileName; // default based on app name
//
Overridables virtual BOOL InitApplication(); virtual BOOL
InitInstance(); virtual int ExitInstance(); // return app exit
code virtual int Run(); virtual BOOL OnIdle(LONG lCount); // return
TRUE if more idle processing virtual LRESULT
ProcessWndProcException(CException* e,const MSG*
pMsg);
public: virtual
~CWinApp(); protected: DECLARE_MESSAGE_MAP() }; | SDK程序的WinMain
所完成的工作現(xiàn)在由CWinApp 的三個(gè)函數(shù)完成:
virtual BOOL InitApplication(); virtual BOOL InitInstance(); virtual
int Run(); | "CMFCThreadApp
theApp;"語(yǔ)句定義的全局變量theApp是整個(gè)程式的application object,每一個(gè)MFC
應(yīng)用程序都有一個(gè)。當(dāng)我們執(zhí)行MFCThread程序的時(shí)候,這個(gè)全局變量被構(gòu)造。theApp
配置完成后,WinMain開(kāi)始執(zhí)行。但是程序中并沒(méi)有WinMain的代碼,它在哪里呢?原來(lái)MFC早已準(zhǔn)備好并由Linker直接加到應(yīng)用程序代碼中的,其原型為(存在于VC++6.0安裝目錄下提供的APPMODUL.CPP文件中):
extern "C" int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE
hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // call
shared/exported WinMain return AfxWinMain(hInstance, hPrevInstance,
lpCmdLine,
nCmdShow); } | 其中調(diào)用的AfxWinMain如下(存在于VC++6.0安裝目錄下提供的WINMAIN.CPP文件中):
int AFXAPI AfxWinMain(HINSTANCE hInstance, HINSTANCE
hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { ASSERT(hPrevInstance
== NULL);
int nReturnCode = -1; CWinThread* pThread =
AfxGetThread(); CWinApp* pApp = AfxGetApp();
// AFX internal
initialization if (!AfxWinInit(hInstance, hPrevInstance, lpCmdLine,
nCmdShow)) goto InitFailure;
// App global initializations
(rare) if (pApp != NULL && !pApp->InitApplication()) goto
InitFailure;
// Perform specific initializations if
(!pThread->InitInstance()) { if (pThread->m_pMainWnd !=
NULL) { TRACE0("Warning: Destroying non-NULL
m_pMainWnd\n"); pThread->m_pMainWnd->DestroyWindow(); } nReturnCode
= pThread->ExitInstance(); goto InitFailure; } nReturnCode =
pThread->Run();
InitFailure: #ifdef _DEBUG // Check for
missing AfxLockTempMap calls if
(AfxGetModuleThreadState()->m_nTempMapLock !=
0) { TRACE1("Warning: Temp map lock count non-zero
(%ld).\n", AfxGetModuleThreadState()->m_nTempMapLock); } AfxLockTempMaps(); AfxUnlockTempMaps(-1); #endif
AfxWinTerm(); return
nReturnCode; } | 我們提取主干,實(shí)際上,這個(gè)函數(shù)做的事情主要是:
CWinThread* pThread = AfxGetThread(); CWinApp* pApp =
AfxGetApp(); AfxWinInit(hInstance, hPrevInstance, lpCmdLine,
nCmdShow) pApp->InitApplication() pThread->InitInstance() pThread->Run(); | 其中,InitApplication
是注冊(cè)窗口類(lèi)別的場(chǎng)所;InitInstance是產(chǎn)生窗口并顯示窗口的場(chǎng)所;Run是提取并分派消息的場(chǎng)所。這樣,MFC就同WIN32
SDK程序?qū)?yīng)起來(lái)了。CWinThread::Run是程序生命的"活水源頭"(侯捷:《深入淺出MFC》,函數(shù)存在于VC++
6.0安裝目錄下提供的THRDCORE.CPP文件中):
// main running routine until thread exits int
CWinThread::Run() { ASSERT_VALID(this);
// for tracking the idle
time state BOOL bIdle = TRUE; LONG lIdleCount = 0;
// acquire
and dispatch messages until a WM_QUIT message is received. for
(;;) { // phase1: check to see if we can do idle work while (bIdle
&& !::PeekMessage(&m_msgCur, NULL, NULL, NULL,
PM_NOREMOVE)) { // call OnIdle while in bIdle state if
(!OnIdle(lIdleCount++)) bIdle = FALSE; // assume "no idle"
state }
// phase2: pump messages while
available do { // pump message, but quit on WM_QUIT if
(!PumpMessage()) return ExitInstance();
// reset "no idle"
state after pumping "normal" message if
(IsIdleMessage(&m_msgCur)) { bIdle = TRUE; lIdleCount =
0; }
} while (::PeekMessage(&m_msgCur, NULL, NULL, NULL,
PM_NOREMOVE)); } ASSERT(FALSE); // not
reachable } | 其中的PumpMessage函數(shù)又對(duì)應(yīng)于:
///////////////////////////////////////////////////////////////////////////// //
CWinThread implementation helpers
BOOL
CWinThread::PumpMessage() { ASSERT_VALID(this);
if
(!::GetMessage(&m_msgCur, NULL, NULL, NULL)) { return
FALSE; }
// process this message if(m_msgCur.message !=
WM_KICKIDLE &&
!PreTranslateMessage(&m_msgCur)) { ::TranslateMessage(&m_msgCur); ::DispatchMessage(&m_msgCur); } return
TRUE; } | 因此,忽略IDLE狀態(tài),整個(gè)RUN的執(zhí)行提取主干就是:
do
{ ::GetMessage(&msg,...); PreTranslateMessage{&msg); ::TranslateMessage(&msg); ::DispatchMessage(&msg); ... }
while
(::PeekMessage(...)); | 由此,我們建立了MFC消息獲取和派生機(jī)制與WIN32
SDK程序之間的對(duì)應(yīng)關(guān)系。下面繼續(xù)分析MFC消息的"繞行"過(guò)程。 在MFC中,只要是CWnd
衍生類(lèi)別,就可以攔下任何Windows消息。與窗口無(wú)關(guān)的MFC類(lèi)別(例如CDocument
和CWinApp)如果也想處理消息,必須衍生自CCmdTarget,并且只可能收到WM_COMMAND消息。所有能進(jìn)行MESSAGE_MAP的類(lèi)都繼承自CCmdTarget,如:
MFC中MESSAGE_MAP的定義依賴(lài)于以下三個(gè)宏:
DECLARE_MESSAGE_MAP()
BEGIN_MESSAGE_MAP( theClass, //Specifies
the name of the class whose message map this is baseClass //Specifies the
name of the base class of
theClass )
END_MESSAGE_MAP() | 我們程序中涉及到的有:MFCThread.h、MainFrm.h、ChildView.h文件
DECLARE_MESSAGE_MAP() MFCThread.cpp文件 BEGIN_MESSAGE_MAP(CMFCThreadApp,
CWinApp) //{{AFX_MSG_MAP(CMFCThreadApp) ON_COMMAND(ID_APP_ABOUT,
OnAppAbout) // NOTE - the ClassWizard will add and remove mapping macros
here. // DO NOT EDIT what you see in these blocks of generated
code! //}}AFX_MSG_MAP END_MESSAGE_MAP() MainFrm.cpp文件 BEGIN_MESSAGE_MAP(CMainFrame,
CFrameWnd) //{{AFX_MSG_MAP(CMainFrame) // NOTE - the ClassWizard will add
and remove mapping macros here. // DO NOT EDIT what you see in these blocks
of generated code
! ON_WM_SETFOCUS() //}}AFX_MSG_MAP END_MESSAGE_MAP() ChildView.cpp文件 BEGIN_MESSAGE_MAP(CChildView,CWnd
) //{{AFX_MSG_MAP(CChildView) ON_WM_PAINT() //}}AFX_MSG_MAP END_MESSAGE_MAP() | 由這些宏,MFC建立了一個(gè)消息映射表(消息流動(dòng)網(wǎng)),按照消息流動(dòng)網(wǎng)匹配對(duì)應(yīng)的消息處理函數(shù),完成整個(gè)消息的"繞行"。 看到這里相信你有這樣的疑問(wèn):程序定義了CWinApp類(lèi)的theApp全局變量,可是從來(lái)沒(méi)有調(diào)用AfxBeginThread或theApp.CreateThread啟動(dòng)線程呀,theApp對(duì)應(yīng)的線程是怎么啟動(dòng)的? 答:MFC在這里用了很高明的一招。實(shí)際上,程序開(kāi)始運(yùn)行,第一個(gè)線程是由操作系統(tǒng)(OS)啟動(dòng)的,在CWinApp的構(gòu)造函數(shù)里,MFC將theApp"對(duì)應(yīng)"向了這個(gè)線程,具體的實(shí)現(xiàn)是這樣的:
CWinApp::CWinApp(LPCTSTR lpszAppName) { if (lpszAppName !=
NULL) m_pszAppName = _tcsdup(lpszAppName); else m_pszAppName =
NULL;
// initialize CWinThread state AFX_MODULE_STATE *pModuleState
= _AFX_CMDTARGET_GETSTATE(); AFX_MODULE_THREAD_STATE *pThreadState =
pModuleState->m_thread; ASSERT(AfxGetThread() ==
NULL); pThreadState->m_pCurrentWinThread =
this; ASSERT(AfxGetThread() == this); m_hThread =
::GetCurrentThread(); m_nThreadID = ::GetCurrentThreadId();
//
initialize CWinApp state ASSERT(afxCurrentWinApp == NULL); // only one
CWinApp object please pModuleState->m_pCurrentWinApp =
this; ASSERT(AfxGetApp() == this);
// in non-running state until
WinMain m_hInstance = NULL; m_pszHelpFilePath =
NULL; m_pszProfileName = NULL; m_pszRegistryKey = NULL; m_pszExeName
= NULL; m_pRecentFileList = NULL; m_pDocManager = NULL; m_atomApp =
m_atomSystemTopic = NULL; //微軟懶鬼?或者他認(rèn)為 //這樣連等含義更明確? m_lpCmdLine =
NULL; m_pCmdInfo = NULL;
// initialize wait cursor
state m_nWaitCursorCount = 0; m_hcurWaitCursorRestore = NULL;
//
initialize current printer state m_hDevMode = NULL; m_hDevNames =
NULL; m_nNumPreviewPages = 0; // not specified (defaults to 1)
//
initialize DAO state m_lpfnDaoTerm = NULL; // will be set if AfxDaoInit
called
// other initialization m_bHelpMode =
FALSE; m_nSafetyPoolSize = 512; // default
size } | 很顯然,theApp成員變量都被賦予OS啟動(dòng)的這個(gè)當(dāng)前線程相關(guān)的值,如代碼:
m_hThread = ::GetCurrentThread();//theApp的線程句柄等于當(dāng)前線程句柄 m_nThreadID =
::GetCurrentThreadId();//theApp的線程ID等于當(dāng)前線程ID | 所以CWinApp類(lèi)幾乎只是為MFC程序的第一個(gè)線程量身定制的,它不需要也不能被AfxBeginThread或theApp.CreateThread"再次"啟動(dòng)。這就是CWinApp類(lèi)和theApp全局變量的內(nèi)涵!如果你要再增加一個(gè)UI線程,不要繼承類(lèi)CWinApp,而應(yīng)繼承類(lèi)CWinThread。而參考第1節(jié),由于我們一般以主線程(在MFC程序里實(shí)際上就是OS啟動(dòng)的第一個(gè)線程)處理所有窗口的消息,所以我們幾乎沒(méi)有再啟動(dòng)UI線程的需求! 深入淺出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ī)通過(guò)串口進(jìn)行通信。因此,操作和使用PC的串口成為大多數(shù)單片機(jī)、嵌入式系統(tǒng)領(lǐng)域工程師必須具備的能力。
串口的使用需要通過(guò)三個(gè)步驟來(lái)完成的:
?。?)
打開(kāi)通信端口;
?。?)
初始化串口,設(shè)置波特率、數(shù)據(jù)位、停止位、奇偶校驗(yàn)等參數(shù)。為了給讀者一個(gè)直觀的印象,下圖從Windows的"控制面板->系統(tǒng)->設(shè)備管理器->通信端口(COM1)"打開(kāi)COM的設(shè)置窗口:

?。?)
讀寫(xiě)串口。
在WIN32平臺(tái)下,對(duì)通信端口進(jìn)行操作跟基本的文件操作一樣。
創(chuàng)建/打開(kāi)COM資源
下列函數(shù)如果調(diào)用成功,則返回一個(gè)標(biāo)識(shí)通信端口的句柄,否則返回-1:
HADLE CreateFile(PCTSTR lpFileName, //通信端口名,如"COM1" WORD dwDesiredAccess,
//對(duì)資源的訪問(wèn)類(lèi)型 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; | 讀寫(xiě)串口
在讀寫(xiě)串口之前,還要用PurgeComm()函數(shù)清空緩沖區(qū),并用SetCommMask
()函數(shù)設(shè)置事件掩模來(lái)監(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ù)來(lái)等待串口上發(fā)生事件,其函數(shù)原型為:
BOOL WaitCommEvent( HANDLE hFile, //標(biāo)識(shí)通信端口的句柄 LPDWORD lpEvtMask,
//指向存放事件標(biāo)識(shí)變量的指針 LPOVERLAPPED lpOverlapped, //
指向overlapped結(jié)構(gòu) ); | 我們可以在發(fā)生事件后,根據(jù)相應(yīng)的事件類(lèi)型,進(jìn)行串口的讀寫(xiě)操作:
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, //需要寫(xiě)的字節(jié)數(shù) LPDWORD
lpNumberOfBytesWritten, //實(shí)際寫(xiě)入的字節(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)化問(wè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(); //打開(kāi)并設(shè)置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)并設(shè)置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; } | 此后我們?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ù)事件類(lèi)型和自身緩沖區(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寫(xiě)入數(shù)據(jù) DWORD wCount;
//寫(xiě)入的字節(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寫(xiě)入數(shù)據(jù) DWORD wCount;
//寫(xiě)入的字節(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.多線程串口類(lèi)
使用多線程串口通信更方便的途徑是編寫(xiě)一個(gè)多線程的串口類(lèi),例如Remon
Spekreijse編寫(xiě)了一個(gè)CSerialPort串口類(lèi)。仔細(xì)分析這個(gè)類(lèi)的源代碼,將十分有助于我們對(duì)先前所學(xué)多線程及同步知識(shí)的理解。
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í)現(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ù)中,將打開(kāi)串口,設(shè)置相關(guān)參數(shù),并創(chuàng)建串口相關(guān)的用戶(hù)控制事件,初始化臨界區(qū)(Critical
Section),以成隊(duì)的EnterCriticalSection()、LeaveCriticalSection()函數(shù)進(jìn)行資源的排它性訪問(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核心函數(shù):串口線程控制函數(shù)
串口線程處理函數(shù)是整個(gè)類(lèi)中最核心的部分,它主要完成兩類(lèi)工作:
?。?)利用WaitCommEvent函數(shù)對(duì)串口上發(fā)生的事件進(jìn)行獲取并根據(jù)事件的不同類(lèi)型進(jìn)行相應(yīng)的處理;
(2)利用WaitForMultipleObjects函數(shù)對(duì)串口相關(guān)的用戶(hù)控制事件進(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讀寫(xiě)串口
下面一組函數(shù)是用戶(hù)對(duì)串口進(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控制接口
應(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類(lèi)對(duì)我們理解多線程及其同步機(jī)制是大有益處的,從http://codeguru./network/serialport.shtml我們可以獲取CSerialPort類(lèi)的介紹與工程實(shí)例。另外,電子工業(yè)出版社《Visual
C++/Turbo
C串口通信編程實(shí)踐》一書(shū)的作者龔建偉也編寫(xiě)了一個(gè)使用CSerialPort類(lèi)的例子,可以從http://www./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ú)自和客戶(hù)方發(fā)生連接并處理異常。
使用這種方法的優(yōu)點(diǎn)是:
?。?)可以較快地實(shí)現(xiàn)原型設(shè)計(jì),尤其在用戶(hù)數(shù)目較少、連接保持時(shí)間較長(zhǎng)時(shí)有表現(xiàn)較好;
?。?)主線程不與子線程發(fā)生通信,在一定程度上減少了系統(tǒng)資源的消耗。
其缺點(diǎn)是:
?。?)生成和終止子線程的開(kāi)銷(xiāo)比較大;
?。?)對(duì)遠(yuǎn)端用戶(hù)的控制較弱。
這種多線程方式總的特點(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)度。一旦客戶(hù)發(fā)出連接請(qǐng)求,主線程將從線程池中查找一個(gè)懸掛的子線程:
?。?)如果找到,主線程將該連接分配給這個(gè)被發(fā)現(xiàn)的子線程。子線程從主線程處接管該連接,并與用戶(hù)通信。當(dāng)連接結(jié)束時(shí),該子線程將自動(dòng)懸掛,并進(jìn)人線程池等待再次被調(diào)度;
?。?)如果當(dāng)前已沒(méi)有可用的子線程,主線程將通告發(fā)起連接的客戶(hù)。
使用這種方法進(jìn)行設(shè)計(jì)的優(yōu)點(diǎn)是:
?。?)主線程可以更好地對(duì)派生的子線程進(jìn)行控制和調(diào)度;
?。?)對(duì)遠(yuǎn)程用戶(hù)的監(jiān)控和管理能力較強(qiáng)。
雖然主線程對(duì)子線程的調(diào)度要消耗一定的資源,但是與主監(jiān)控線程方式中派生和終止線程所要耗費(fèi)的資源相比,要少很多。因此,使用該種方法設(shè)計(jì)和實(shí)現(xiàn)的系統(tǒng)在客戶(hù)端連接和終止變更頻繁時(shí)有上佳表現(xiàn)。
這種多線程方式總的特點(diǎn)是"靜態(tài)生成,動(dòng)態(tài)調(diào)度"。
| |
|