您的位置:首页 > 其它

进程互斥

2016-06-01 19:33 197 查看
代码及运行结果:
#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
;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: