关闭

进程互斥

76人阅读 评论(0) 收藏 举报
分类:

代码及运行结果:

#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;

}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7184次
    • 积分:173
    • 等级:
    • 排名:千里之外
    • 原创:11篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类