CPP线程_互斥锁

 1 #define _CRT_SECURE_NO_WARNINGS /* VS2013,2015需要这一行 */
 2 #include <stdio.h>
 3 
 4 #include "osapi/osapi.h"
 5 
 6 OS_Mutex g_mutex;//定义互斥锁
 7 char g_key[16]; // Generator更新它,Checker获取它
 8 
 9 class KeyGenerator : public OS_Thread
10 {
11 private:
12     virtual int Routine()
13     {
14         int times = 0;
15         while(1)
16         {
17             // 生成key: 需要80ms
18             char key_new[16];            
19             for(int i=0; i<16; i++)
20             {
21                 OS_Thread::Msleep(5);
22                 key_new[i] = times;
23             }
24 
25             // 更新key: 占有锁的时间非常短
26             g_mutex.Lock();//创建锁
27             memcpy(g_key, key_new, 16);
28             g_mutex.Unlock();//释放锁
29 
30             times ++;
31             if(times >= 128) times = 0;
32             //OS_Thread::Msleep(50);
33         }
34         return 0; 
35     }
36 };
37 
38 class KeyChecker : public OS_Thread
39 {
40 private:
41     // 线程主函数
42     virtual int Routine()
43     {
44         while(1)
45         {        
46             // 尽量缩短对共享数据的访问时间
47             char copy[16];
48             g_mutex.Lock();
49             memcpy(copy, g_key, 16);
50             g_mutex.Unlock();
51 
52             // 数据处理
53             // 检查完整性            
54             for(int i=1; i<16; i++)
55             {
56                 if(copy[i] != copy[i-1])
57                 {
58                     printf("不完整!!\n");
59                     PrintKey();
60                     //return 0;
61                 }
62             }            
63 
64             //OS_Thread::Msleep(50);
65         }
66         return 0; // 正常退出
67     }
68 
69     void PrintKey()
70     {
71         printf("Key: ");
72         for(int i=0; i<16; i++)
73             printf("%02X ", g_key[i]);                    
74         printf("\n");
75     }
76 };
77 
78 
79 int main()
80 {
81     KeyGenerator a;
82     a.Run();
83 
84     KeyChecker b;
85     b.Run();
86 
87     getchar();
88 
89 
90     return 0;
91 }

 

posted on 2017-12-18 12:47  Doctor_uee  阅读(358)  评论(0)    收藏  举报

导航