WIN32線程控制主要實(shí)現(xiàn)線程的創(chuàng)建、終止、掛起和恢復(fù)等操作,這些操作都依賴于WIN32提供的一組API和具體編譯器的C運(yùn)行時(shí)庫(kù)函數(shù)。
1.線程函數(shù)
在啟動(dòng)一個(gè)線程之前,必須為線程編寫一個(gè)全局的線程函數(shù),這個(gè)線程函數(shù)接受一個(gè)32位的LPVOID作為參數(shù),返回一個(gè)UINT,線程函數(shù)的結(jié)構(gòu)為:
UINT ThreadFunction(LPVOID pParam) { //線程處理代碼 return0; } |
while(1) { WaitForSingleObject(…,…);//或WaitForMultipleObjects(…) //Do something } |
#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; } |
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 |
#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; } |
#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; } |
2.創(chuàng)建線程
進(jìn)程的主線程由操作系統(tǒng)自動(dò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 ); |
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 ); |
VOID ExitThread(UINT fuExitCode ); |
BOOL TerminateThread(HANDLE hThread,DWORD dwExitCode); |
DWORD ResumeThread(HANDLE hThread); |
DWORD SuspendThread(HANDLE hThread); |
5.設(shè)置線程優(yōu)先級(jí)
當(dāng)一個(gè)線程被首次創(chuàng)建時(shí),它的優(yōu)先級(jí)等同于它所屬進(jìn)程的優(yōu)先級(jí)。在單個(gè)進(jìn)程內(nèi)可以通過調(diào)用SetThreadPriority函數(shù)改變線程的相對(duì)優(yōu)先級(jí)。一個(gè)線程的優(yōu)先級(jí)是相對(duì)于其所屬進(jìn)程的優(yōu)先級(jí)而言的。
BOOL SetThreadPriority(HANDLE hThread, int nPriority); |
![]() |
![]() |
HANDLE hCurrentThread = GetCurrentThread(); //獲得該線程句柄 SetThreadPriority(hCurrentThread, THREAD_PRIORITY_LOWEST); |
VOID Sleep(DWORD dwMilliseconds); |
Int GetThreadPriority (HANDLE hThread); |
BOOL WINAPI GetExitCodeThread( HANDLE hThread, LPDWORD lpExitCode ); |
獲得/設(shè)置線程上下文 BOOL WINAPI GetThreadContext( HANDLE hThread, LPCONTEXT lpContext ); BOOL WINAPI SetThreadContext( HANDLE hThread, CONST CONTEXT *lpContext ); |
#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; } |
#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; } |
![]() ![]() ![]() |
#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); } |
聯(lián)系客服