CPP_信号量

 1 #define _CRT_SECURE_NO_WARNINGS /* VS2013,2015需要这一行 */
 2 #include <stdio.h>
 3 #include <time.h>
 4 #include <stdlib.h>
 5 #include "osapi/osapi.h"
 6 
 7 
 8 OS_Mutex g_mutex;
 9 int g_buf[100]; // 缓冲区:最多存放100个数
10 int g_count = 0;
11 
12 OS_Semaphore g_sem(0);//定义信号量
13 
14 // 第一个线程:生产者
15 class Producer : public OS_Thread
16 {
17 public:
18     int Routine()
19     {
20         while(1)
21         {
22             int r = rand() % 20 + 1; // 生成一个1..20之间的随机数
23             OS_Thread::Msleep(50 * r); // 睡觉的间隔50-1000毫秒
24 
25             // 存放一个物品(这里就是存一个数, 代表一下物品的意思)
26             g_mutex.Lock();
27             g_buf[g_count] = r;
28             g_count ++;
29             printf("放入物品: %d \n", r);
30             g_mutex.Unlock();
31 
32             g_sem.Post(); // 把信号量的值加1
33         }
34         return 0;
35     }
36 };
37 
38 // 第二个线程:消费者
39 class Consumer : public OS_Thread
40 {
41 public:
42     int Routine()
43     {
44     
45         while(1)
46         {
47             //OS_Thread::Msleep(800); // 信号量机制不用sleep
48             g_sem.Wait(); // 信号量减1
49 
50             g_mutex.Lock();
51             if(g_count > 0)
52             {
53                 for(int i=0; i<g_count; i++)
54                 {
55                     printf(" ==== 消费物品: %d \n", g_buf[i]);
56                 }
57                 g_count = 0;
58             }
59             g_mutex.Unlock();
60         }
61         return 0;
62     }
63 };
64 
65 int main()
66 {
67     srand(time(NULL));
68 
69     // 启动第一个线程
70     Producer p;
71     p.Run();
72 
73     // 启动第二个线程
74     Consumer c;
75     c.Run();
76 
77     // 按回车退出程序
78     getchar();
79     return 0;
80 }

 

posted on 2017-12-19 18:02  Doctor_uee  阅读(242)  评论(0)    收藏  举报

导航