windows系統調用 臨界區機制

來源:互聯網
上載者:User

標籤:style   class   blog   code   color   get   

 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         NULL63         );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         NULL73         );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 }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.