Test.cpp:Defines the entry point for the console application.//#include "stdafx.h" #include <iostream>using name Space Std; #define LEFT (N) ((n+4)%5) #define RIGHT (n) ((n+1)%5) class Mysemaphore{public:mysemaphore::mysemaphore (Long Ninitcount) {M_sem = CreateSemaphore (null,ninitcount,maxlong32,null);} BOOL Down (DWORD dwmilliseconds) {if (M_sem) {DWORD dwret = WaitForSingleObject (m_sem,dwmilliseconds); if (wait_object_0 = = Dwret) {return true;}} return false;} BOOL Up () {if (M_sem) {return ReleaseSemaphore (m_sem,1,null) True:false;} return false;} Private:handle M_sem;}; Enum Personstate{state_thinking,state_waiting,state_eating,}; Mysemaphore Personarr[5] = {0,0,0,0,0}; Personstate Statearr[5] = {state_thinking,state_thinking,state_thinking,state_thinking,state_thinking}; Mysemaphore Mutex = 1;void Test (int nIndex) {if (statearr[nindex] = = state_waiting &&statearr[left (nIndex)]! = STA Te_eating&&statearr[right (nIndex)]! = state_eating) {Statearr[nindex] = State_eating;personarR[nindex].up ();}} void take_fork (int nIndex) {mutex.down (INFINITE); Statearr[nindex] = State_waiting;test (NIndex); Mutex.up ();p Ersonarr [Nindex].down (INFINITE);} void put_fork (int nIndex) {mutex.down (INFINITE); Statearr[nindex] = state_thinking;printf ("Person%d put fork and Thinking\n ", nindex+1); Test (left (nIndex)); Test (right (NIndex)); Mutex.up ();} DWORD WINAPI Personproc (lpvoid lpparam) {int nthreadindex = (int) lpparam;for (;;) {take_fork (Nthreadindex);p rintf ("person%d take fork and eating\n", nthreadindex+1); Sleep (1000); Eating;put_fork (Nthreadindex);} return 0;} int _tmain (int argc, _tchar* argv[]) {HANDLE athread[5];for (int i=0; i < 5; i++) {Athread[i] = CreateThread (NULL, Default security Attributes0,//default stack size (lpthread_start_routine) Personproc, (void*) I,//No Thread function Arguments0,//default creation Flagsnull); Receive thread Identifierif (athread[i] = = NULL) {printf ("CreateThread Error:%d\n", GetLastError ()); return 1;}} Sleep (-1);return 0;}
Specific analysis reference < modern operating system > related chapters
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Philosopher's Dining problem code