C語言 多線程測試


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("\n我是子線程:%d\n",pM);
12     printf("子線程的線程ID號為:%d\n", GetCurrentThreadId());  
13     return 0;  
14 } 
15 
16 int _tmain(int argc, _TCHAR* argv[])
17 {
18     printf("我是主線程\n");
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\n",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 }

 測試結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM