深入淺出Win32多線程程序設(shè)計(jì)之線程控制
作者:宋寶華出處:天極開(kāi)發(fā)責(zé)任編輯:
方舟 [ 2005-12-15 09:04 ]
WIN32線程控制主要實(shí)現(xiàn)線程的創(chuàng)建、終止、掛起和恢復(fù)等操作,這些操作都依賴于WIN32提供的一組API和具體編譯器的C運(yùn)行時(shí)庫(kù)函數(shù)。
WIN32線程控制主要實(shí)現(xiàn)線程的創(chuàng)建、終止、掛起和
恢復(fù)等操作,這些操作都依賴于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ù),通常有如下解決方案:
?。?)將該成員函數(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)成員。
?。?)不定義類(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;
}
?。?)可以對(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)完成用戶線程的創(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)似,但有如下差異:
?。?)通過(guò)_beginthread函數(shù)我們可以利用其參數(shù)列表arglist將多個(gè)參數(shù)傳遞到線程;
(2)_beginthread 函數(shù)初始化某些 C 運(yùn)行時(shí)庫(kù)變量,在線程中若需要使用 C 運(yùn)行時(shí)庫(kù)。
3.終止線程
線程的終止有如下四種方式:
(1)線程函數(shù)返回;
?。?)線程自身調(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)的條件終止很有用。例如,專門(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;
?。?)正常: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;
(4)正常線程:THREAD_PRIORITY_ NORMAL (缺省);
?。?)高于正常線程:THREAD_PRIORITY_ABOVE_NORMAL;
?。?)最高線程:THREAD_PRIORITY_HIGHEST;
(7)關(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);
}