线程控制
三个函数的使用
1,WaitForSingleObject
#include <Windows.h> DWORD WINAPI MyThread(LPVOID lpParameter) { //ziji de code } int main() { HANDLE hThread; hThread = CreateThread(NULL,0,MyThread,NULL,0,NULL); CloseHandle(hThread); WaitForSingleObject(hThread,INFINITE);//等待hThread线程执行完毕再往下走 printf("hThread线程执行完毕。。。"); return 0; }
2,WaitForMultipleObjects
DWORD WaitForMultipleObjects( DWORD nCount, const HANDLE *lpHandles, BOOL bWaitAll,//TRUE-所有线程状态发生改变时,FALSE-任何一个线程状态发生改变时 DWORD dwMilliseconds );
3,GetExitCodeThread
获取线程返回值,根据返回值,判断如何执行后续代码
#include <Windows.h> DWORD WINAPI MyThread1(LPVOID lpParameter) { DWORD oneCode; //ziji de code return oneCode; } DWORD WINAPI MyThread2(LPVOID lpParameter) { DWORD oneCode; //ziji de code return oneCode; } int main() { HANDLE hThread1; HANDLE hThread2; DWORD dwThreadResult1; DWORD dwThreadResult2; //创建多个线程,可以使用同一份线程代码,创建的是不同的堆栈,下面都使用了MyThread线程函数的代码 hThread1 = CreateThread(NULL,0,MyThread1,NULL,0,NULL); hThread2 = CreateThread(NULL,0,MyThread2,NULL,0,NULL); GetExitCodeThread(hThread1,&dwThreadResult1);//获取线程返回值,根据返回值,执行后续代码 if ...if ... GetExitCodeThread(hThread2,&dwThreadResult2); CloseHandle(hThread1); CloseHandle(hThread2); return 0; }