开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上,要求输出结果必须按ABC的顺序显示:ABCABC

 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 }

 

posted @ 2017-08-15 08:20  wwsea  阅读(934)  评论(0编辑  收藏  举报