windows系统调用 临界区机制

时间:2014-06-18 14:23:43   收藏:0   阅读:205
 1 #include "iostream"
 2 #include "windows.h"
 3 #include "cstring"
 4 using namespace std;
 5 
 6 
 7 static int g_nIndex=0;
 8 const int MAX_TIMES=10;
 9 static DWORD g_dwTimes;
10 CRITICAL_SECTION g_CriticalSection;
11 
12 DWORD WINAPI IncProc(LPVOID lpParam){
13     BOOL fDone=FALSE;
14     while(!fDone){
15         EnterCriticalSection(&g_CriticalSection);
16         if(g_nIndex>=MAX_TIMES){
17             fDone=TRUE;
18 
19         }
20         else{
21             g_dwTimes++;
22             printf("The Inc count‘s value is%d.\n",g_dwTimes);
23             g_nIndex++;
24             Sleep(10);
25         }
26         LeaveCriticalSection(&g_CriticalSection);
27     }
28 
29     return(0);
30 }
31 
32 DWORD WINAPI DecProc(LPVOID lpParam){
33     BOOL fDone=FALSE;
34     while(!fDone){
35         EnterCriticalSection(&g_CriticalSection);
36         if(g_nIndex>=MAX_TIMES){
37             fDone=TRUE;
38         }
39         else{
40         g_dwTimes--;
41         printf("The Dec count‘s value id %d.\n",g_dwTimes);
42         g_nIndex++;
43         Sleep(10);
44         }
45         LeaveCriticalSection(&g_CriticalSection);
46     }
47 
48     return(0);
49 }
50 
51 void main(){
52     HANDLE hThread[2];
53 
54     InitializeCriticalSection(&g_CriticalSection);
55 
56     hThread[0]=CreateThread(
57         NULL,
58         0,
59         IncProc,
60         reinterpret_cast<LPVOID>(2),
61         0,
62         NULL
63         );
64     printf("Thread0 is Created!\n");
65 
66     hThread[1]=CreateThread(
67         NULL,
68         0,
69         DecProc,
70         reinterpret_cast<LPVOID>(2),
71         0,
72         NULL
73         );
74     printf("Thread1 is Created!\n");
75 
76     printf("Both Threads are ready into critical section!\n");
77 
78     WaitForMultipleObjects(2,hThread,TRUE,INFINITE);
79 
80     CloseHandle(hThread[1]);
81     CloseHandle(hThread[0]);
82 
83     DeleteCriticalSection(&g_CriticalSection);
84 
85     getchar();
86 }

 

windows系统调用 临界区机制,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!