代碼及運行結果:
#include "windows.h"
#include "process.h"
#include<iostream>
#define N 5 //順時針排序
#define R(x) (x)
#define L(x) ((x+1)%N)
using namespace std;
HANDLE hMutex[N];
HANDLE Mutex;
void pick_up(int me)
{
if(me==0)
{
WaitForSingleObject(hMutex[L(me)],INFINITE);//等左邊筷子
WaitForSingleObject(Mutex,INFINITE);
cout<<"No."<<me<<"Philosopher pick up left No."<<L(me)<<"chopstick"<<endl;
ReleaseMutex(Mutex);
Sleep(500);
WaitForSingleObject(hMutex[R(me)],INFINITE);//等右邊筷子
WaitForSingleObject(Mutex,INFINITE);
cout<<"No."<<me<<"Philosopher pick up rightNo."<<R(me)<<" chopstick"<<endl;
ReleaseMutex(Mutex);
Sleep(500);
}
else
{
WaitForSingleObject(hMutex[R(me)],INFINITE);//等右邊筷子
WaitForSingleObject(Mutex,INFINITE);
cout<<"No."<<me<<"Philosopher pick up rightNo."<<R(me)<<" chopstick"<<endl;
ReleaseMutex(Mutex);
Sleep(500);
WaitForSingleObject(hMutex[L(me)],INFINITE);//等左邊筷子
WaitForSingleObject(Mutex,INFINITE);
cout<<"No."<<me<<"Philosopher pick up left No."<<L(me)<<"chopstick"<<endl;
ReleaseMutex(Mutex);
Sleep(500);
}
}
void put_down(int me)
{
ReleaseMutex(hMutex[R(me)]);
WaitForSingleObject(Mutex,INFINITE);
cout<<"No."<<me<<"Philosopher put down right No."<<R(me)<<"chopstick"<<endl;
ReleaseMutex(Mutex);
ReleaseMutex(hMutex[L(me)]);
WaitForSingleObject(Mutex,INFINITE);
cout<<"No."<<me<<"Philosopher put down left No."<<L(me)<<" chopstick"<<endl;
ReleaseMutex(Mutex);
}
DWORD WINAPI PhilosopherThread(LPVOIDlpParameter)
{
int*me=(int *)lpParameter;
while(1)
{
pick_up(*me);
WaitForSingleObject(Mutex,INFINITE);
cout<<"No."<<*me<<"Philosopher is eating..."<<endl;
ReleaseMutex(Mutex);
Sleep(500);
put_down(*me);
WaitForSingleObject(Mutex,INFINITE);
cout<<"No."<<*me<<"Philosopher is thinking..."<<endl;
ReleaseMutex(Mutex);
Sleep(500);
}
return 1;
}
int main(int argc, char* argv[])
{
intThrdNo[5];
inti;
Mutex=CreateMutex(NULL,FALSE,NULL);
for(i=0;i<N;i++)hMutex[i]=CreateMutex(NULL,FALSE,NULL);
for(i=0;i<N;i++)
{
ThrdNo[i]=i;
CreateThread(NULL,0,PhilosopherThread,&ThrdNo[i],NULL,NULL);
}
Sleep(10000);
return0;
}