1. 程式人生 > >開啟3個線程,這3個線程的ID分別為A、B、C,每個線程將自己的ID在屏幕上,要求輸出結果必須按ABC的順序顯示:ABCABC

開啟3個線程,這3個線程的ID分別為A、B、C,每個線程將自己的ID在屏幕上,要求輸出結果必須按ABC的順序顯示:ABCABC

abc multi adf ++ include vol form 主線程 tdi

 1 #include <stdio.h>
 2 #include <process.h>
 3 #include <windows.h>
 4 
 5 //線程個數
 6 const int THREAD_NUM = 3;
 7 
 8 //循環次數
 9 const int LOOP = 10;
10 
11 //互斥事件
12 HANDLE g_hThreadEvent[THREAD_NUM];//子線程同步事件
13 HANDLE g_Semaphore;               //主線程與子線程同步
14 //volatile int g_Count = 0;
15 int
g_Count = 0; 16 17 unsigned int __stdcall ThreadFunction(void *pPM) 18 { 19 int num = *(int*)pPM; 20 ReleaseSemaphore(g_Semaphore, 1, NULL); //信號量++ 21 22 for (int i = 0; i < LOOP; i++) 23 { 24 WaitForSingleObject(g_hThreadEvent[num], INFINITE); 25 //InterlockedIncrement((LPLONG)&g_Count);
26 g_Count++; 27 28 printf("第%d次 線程ID:%3d,線程打印:%c\n ", g_Count, GetCurrentThreadId(), num + A); 29 30 SetEvent(g_hThreadEvent[(num + 1) % THREAD_NUM]); 31 } 32 33 return 0; 34 } 35 36 37 int main(void) 38 { 39 int i = 0; 40 HANDLE hThreadHandle[THREAD_NUM];
41 g_Semaphore = CreateSemaphore(NULL, 0, 1, NULL); //當前0個資源,最大允許1個同時訪 42 43 for (i = 0; i < THREAD_NUM; i++) 44 { 45 g_hThreadEvent[i] = CreateEvent(NULL, FALSE, FALSE, NULL); 46 } 47 48 for (i = 0; i < THREAD_NUM; i++) 49 { 50 hThreadHandle[i] = (HANDLE)_beginthreadex(nullptr, 0, ThreadFunction, &i, 0, nullptr); 51 WaitForSingleObject(g_Semaphore, INFINITE); 52 } 53 54 SetEvent(g_hThreadEvent[0]); 55 56 WaitForMultipleObjects(THREAD_NUM, hThreadHandle, true, INFINITE); 57 58 for (i = 0; i < THREAD_NUM; i++) 59 { 60 CloseHandle(hThreadHandle[i]); 61 CloseHandle(g_hThreadEvent[i]); 62 } 63 64 CloseHandle(g_Semaphore); 65 66 return 0; 67 }

開啟3個線程,這3個線程的ID分別為A、B、C,每個線程將自己的ID在屏幕上,要求輸出結果必須按ABC的順序顯示:ABCABC