深入淺出Win32多線程程序設計之線程控制
作者:宋寶華出處:天極開發(fā)責任編輯:
方舟 [ 2005-12-15 09:04 ]
WIN32線程控制主要實現(xiàn)線程的創(chuàng)建、終止、掛起和恢復等操作,這些操作都依賴于WIN32提供的一組API和具體編譯器的C運行時庫函數(shù)。
WIN32線程控制主要實現(xiàn)線程的創(chuàng)建、終止、掛起和
恢復等操作,這些操作都依賴于WIN32提供的一組API和具體編譯器的C運行時
庫函數(shù)。
1.線程函數(shù)
在啟動一個線程之前,必須為線程編寫一個全局的線程函數(shù),這個線程函數(shù)接受一個32位的LPVOID作為參數(shù),返回一個UINT,線程函數(shù)的結構為:
UINT ThreadFunction(LPVOID pParam)
{
//線程處理代碼
return0;
}
在線程處理代碼部分通常包括一個死循環(huán),該循環(huán)中先等待某事情的發(fā)生,再處理相關的工作:
while(1)
{
WaitForSingleObject(…,…);//或WaitForMultipleObjects(…)
//Do something
}
一般來說,C++的類成員函數(shù)不能作為線程函數(shù)。這是因為在類中定義的成員函數(shù),編譯器會給其加上this指針。請看下列程序:
#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;
}
程序編譯時出現(xiàn)如下錯誤:
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;
}
程序編譯時會出錯:
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
如果一定要以類成員函數(shù)作為線程函數(shù),通常有如下解決方案:
(1)將該成員函數(shù)聲明為static類型,
去掉this指針;
我們將上述二個程序改變?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;
}
均編譯通過。
將成員函數(shù)聲明為靜態(tài)雖然可以解決作為線程函數(shù)的問題,但是它帶來了新的問題,那就是static成員函數(shù)只能
訪問static成員。解決此問題的一種途徑是可以在調用類靜態(tài)成員函數(shù)(線程函數(shù))時將this指針作為參數(shù)傳入,并在改線程函數(shù)中用強制類型轉換將this轉換成指向該類的指針,通過該指針訪問非靜態(tài)成員。
?。?)不定義類成員函數(shù)為線程函數(shù),而將線程
函數(shù)定義為類的友元函數(shù)。這樣,線程函數(shù)也可以有類成員函數(shù)同等的權限;
我們將程序修改為:
#include "windows.h"
#include <process.h>
class ExampleTask
{
public:
friend void taskmain(LPVOID param);
void StartTask();
};
void taskmain(LPVOID param)
{
ExampleTask * pTaskMain = (ExampleTask *) param;
//通過pTaskMain指針引用
}
void ExampleTask::StartTask()
{
_beginthread(taskmain,0,this);
}
int main(int argc, char* argv[])
{
ExampleTask realTimeTask;
realTimeTask.StartTask();
return 0;
}
?。?)可以對非靜態(tài)成員函數(shù)實現(xiàn)回調,并訪問非靜態(tài)成員,此法涉及到一些高級技巧,在此不再詳述。
2.創(chuàng)建線程
進程的主線程由操作系統(tǒng)自動生成,Win32提供了CreateThread API來完成用戶線程的創(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++語言編寫多線程應用程序,一定不能使用操作系統(tǒng)提供的CreateThread API,而應該使用C/C++運行時庫中的_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ù)類似,但有如下差異:
?。?)通過_beginthread函數(shù)我們可以利用其參數(shù)列表arglist將多個參數(shù)傳遞到線程;
?。?)_beginthread 函數(shù)初始化某些 C 運行時庫變量,在線程中若需要使用 C 運行時庫。
3.終止線程
線程的終止有如下四種方式:
?。?)線程函數(shù)返回;
?。?)線程自身調用ExitThread 函數(shù)即終止自己,其原型為:
VOID ExitThread(UINT fuExitCode );
它將參數(shù)fuExitCode設置為線程的退出碼。
注意:如果使用C/C++編寫代碼,我們應該使用C/C++運行時庫函數(shù)_endthread (_endthreadex)終止線程,決不能使用ExitThread!
_endthread 函數(shù)對于線程內的條件終止很有用。例如,專門用于通信處理的線程若無法獲取對通信端口的控制,則會退出。
?。?)同一進程或其他進程的線程調用TerminateThread函數(shù),其原型為:
BOOL TerminateThread(HANDLE hThread,DWORD dwExitCode);
該函數(shù)用來結束由hThread參數(shù)指定的線程,并把dwExitCode設成該線程的退出碼。當某個線程不再響應時,我們可以用其他線程調用該函數(shù)來終止這個不響應的線程。
?。?)包含線程的進程終止。
最好使用第1種方式終止線程,第2~4種方式都不宜采用。
4.掛起與恢復線程
當我們創(chuàng)建線程的時候,如果給其傳入CREATE_SUSPENDED標志,則該線程創(chuàng)建后被掛起,我們應使用ResumeThread恢復它:
DWORD ResumeThread(HANDLE hThread);
如果ResumeThread函數(shù)運行成功,它將返回線程的前一個暫停計數(shù),否則返回0x FFFFFFFF。
對于沒有被掛起的線程,程序員可以調用SuspendThread函數(shù)強行掛起之:
DWORD SuspendThread(HANDLE hThread);
一個線程可以被掛起多次。線程可以自行暫停運行,但是不能自行恢復運行。如果一個線程被掛起n次,則該線程也必須被恢復n次才可能得以執(zhí)行。
5.設置線程優(yōu)先級
當一個線程被首次創(chuàng)建時,它的優(yōu)先級等同于它所屬進程的優(yōu)先級。在單個進程內可以通過調用SetThreadPriority函數(shù)改變線程的相對優(yōu)先級。一個線程的優(yōu)先級是相對于其所屬進程的優(yōu)先級而言的。
BOOL SetThreadPriority(HANDLE hThread, int nPriority);
其中參數(shù)hThread是指向待修改優(yōu)先級線程的句柄,線程與包含它的進程的優(yōu)先級關系如下:
線程優(yōu)先級 = 進程類基本優(yōu)先級 + 線程相對優(yōu)先級
進程類的基本優(yōu)先級包括:
(1)實時:REALTIME_PRIORITY_CLASS;
?。?)高:HIGH _PRIORITY_CLASS;
(3)高于正常:ABOVE_NORMAL_PRIORITY_CLASS;
?。?)正常:NORMAL _PRIORITY_CLASS;
(5)低于正常:BELOW_ NORMAL _PRIORITY_CLASS;
?。?)空閑:IDLE_PRIORITY_CLASS。
我們從Win32任務管理器中可以直觀的看到這六個進程類優(yōu)先級,如下圖:
線程的相對優(yōu)先級包括:
(1)空閑:THREAD_PRIORITY_IDLE;
?。?)最低線程:THREAD_PRIORITY_LOWEST;
?。?)低于正常線程:THREAD_PRIORITY_BELOW_NORMAL;
?。?)正常線程:THREAD_PRIORITY_ NORMAL (缺省);
?。?)高于正常線程:THREAD_PRIORITY_ABOVE_NORMAL;
(6)最高線程:THREAD_PRIORITY_HIGHEST;
(7)關鍵時間:THREAD_PRIOTITY_CRITICAL。
下圖給出了進程優(yōu)先級和線程相對優(yōu)先級的映射關系:
例如:
HANDLE hCurrentThread = GetCurrentThread();
//獲得該線程句柄
SetThreadPriority(hCurrentThread, THREAD_PRIORITY_LOWEST);
6.睡眠
VOID Sleep(DWORD dwMilliseconds);
該函數(shù)可使線程暫停自己的運行,直到dwMilliseconds毫秒過去為止。它告訴系統(tǒng),自身不想在某個時間段內被調度。
7.其它重要API
獲得線程優(yōu)先級
一個線程被創(chuàng)建時,就會有一個默認的優(yōu)先級,但是有時要動態(tài)地改變一個線程的優(yōu)先級,有時需獲得一個線程的優(yōu)先級。
Int GetThreadPriority (HANDLE hThread);
如果函數(shù)執(zhí)行發(fā)生錯誤,會返回THREAD_PRIORITY_ERROR_RETURN標志。如果函數(shù)成功地執(zhí)行,會返回優(yōu)先級標志。
獲得線程退出碼
BOOL WINAPI GetExitCodeThread(
HANDLE hThread,
LPDWORD lpExitCode
);
如果執(zhí)行成功,GetExitCodeThread返回TRUE,退出碼被lpExitCode指向內存記錄;否則返回FALSE,我們可通過GetLastError()獲知錯誤原因。如果線程尚未結束,lpExitCode帶回來的將是STILL_ALIVE。
獲得/設置線程上下文
BOOL WINAPI GetThreadContext(
HANDLE hThread,
LPCONTEXT lpContext
);
BOOL WINAPI SetThreadContext(
HANDLE hThread,
CONST CONTEXT *lpContext
);
由于GetThreadContext和SetThreadContext可以操作CPU內部的寄存器,因此在一些高級技巧的編程中有一定應用。譬如,調試器可利用GetThreadContext掛起被調試線程獲取其上下文,并設置上下文中的標志寄存器中的陷阱標志位,最后通過SetThreadContext使設置生效來進行單步調試。
8.實例
以下程序使用CreateThread創(chuàng)建兩個線程,在這兩個線程中Sleep一段時間,主線程通過GetExitCodeThread來判斷兩個線程是否結束運行:
#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;
}
通過下面的程序我們可以看出多線程程序運行順序的難以預料以及WINAPI的CreateThread函數(shù)與C運行時庫的_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;
}
運行的輸出具有很大的隨機性,這里摘取了幾次結果的一部分(幾乎每一次都不同):
如果我們使用標準C庫函數(shù)而不是多線程版的運行時庫,則程序可能輸出"3333444444"這樣的結果,而使用多線程運行時庫后,則可避免這一問題。
下列程序在主線程中創(chuàng)建一個SecondThread,在SecondThread線程中通過自增對Counter計數(shù)到1000000,主線程一直等待其結束:
#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);
}