1、CreateThread 在主线程的基础上创建一个新线程
2、WaitForMultipleObjects 主线程等待子线程
3、CloseHandle 关闭线程
1 // testThread.cpp : 定义控制台应用程序的入口点。 2 3 #include "stdafx.h" 4 #include "windows.h" 5 6 #define MAX_THREADS 3 7 8 //子线程函数 9 DWORD WINAPI ThreadFun(LPVOID pM) 10 { 11 printf(" 我是子线程:%d ",pM); 12 printf("子线程的线程ID号为:%d ", GetCurrentThreadId()); 13 return 0; 14 } 15 16 int _tmain(int argc, _TCHAR* argv[]) 17 { 18 printf("我是主线程 "); 19 20 //HANDLE handle = CreateThread(NULL, 0, ThreadFun, NULL, 0, NULL); 21 //WaitForSingleObject(handle, INFINITE); 22 23 HANDLE hThread[MAX_THREADS]; 24 int i; 25 for(i = 0; i < MAX_THREADS; i++){ 26 hThread[i] = CreateThread(NULL, 0, ThreadFun,(LPVOID *) i, 0, NULL); //创建多线程 27 } 28 if(hThread[i]==NULL) 29 { 30 ExitProcess(i);//退出进程 31 }else{ 32 printf("hThread:,%d ",hThread[i]); 33 } 34 35 WaitForMultipleObjects(MAX_THREADS,hThread,TRUE,INFINITE);//主线程等待子线程结束 36 37 for(i = 0; i < MAX_THREADS; i++){ 38 CloseHandle(hThread[i]);//关闭线程 39 } 40 41 return 0; 42 }
测试结果如下: