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. ",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. ",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! "); 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! "); 75 76 printf("Both Threads are ready into critical section! "); 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 }