首页 > 编程语言 > 详细

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

时间:2017-08-15 09:55:28      阅读:343      评论:0      收藏:0      [点我收藏+]
 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

原文:http://www.cnblogs.com/nalanhairuo/p/7363071.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!