⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 proce3.cpp

📁 这是操作系统中关于进程互斥问题的经典算法源码!很不错的哦!
💻 CPP
字号:
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
static int s=1;
//产生指定范围的整数随机数
int getrand(int min,int max) {
	int m;
	m=(max-min);
    m=min+double(rand())/RAND_MAX*m ;
	return m;
}
int P(int &s)//wait(s) operator
{
 return(--s);
}
int V(int &s)//singal(s) operator
{
 return(++s);
}
void pro_A(int &s)//Process A
{
 void pro_B(int &);
 void pro_C(int &);
 int i;
 cout<<"S="<<s<<endl;
 i=P(s);
 if(i==0)
 { cout<<" A visits the critical scource...; Others must wait!!"<<endl;
   switch(getrand(0,100)%2+1)
   {
    case 1: pro_B(i); pro_C(i); break;
    case 2:pro_C(i);pro_B(i);break;
   }
   cout<<" A had ended!The CS is free now:"<<endl;

 }
 else cout<<"  The CS is being used...; A must wait!"<<endl;
 s=V(i);
}
void pro_B(int &s)//Process B
{
 void pro_C(int &);
 int i;
 cout<<"S="<<s<<endl;
 i=P(s);
 if(i==0)
 { cout<<" B visits the critical scource...; Others must wait!!"<<endl;
   switch(getrand(0,100)%2+1)
   {
   case 1: pro_C(i); pro_A(i);break;
   case 2: pro_A(i);pro_C(i);break;
   }
   cout<<" B had ended!The CS is free now:"<<endl;
 }
 else cout<<"  The CS is being used...; B must wait!"<<endl;
 s=V(i);
}
void pro_C(int &s)//Process C
{
 int i;
 cout<<"S="<<s<<endl;
 i=P(s);
 if(i==0)
 { cout<<" C visits the critical scource...; Others must wait!!"<<endl;
   switch(getrand(0,100)%2+1)
   {
    case 1: pro_A(i); pro_B(i);break;
    case 2: pro_B(i); pro_A(i);break;
   }
   cout<<" C had ended!The CS is free now:"<<endl;

 }
 else cout<<"  The CS is being used...; C must wait!"<<endl;
 s=V(i);
}

void main()
{
 char ch;
 //clrscr();//Clear Screen
 while(1)//CIRCLE
 {
  switch(getrand(0,100)%3+1)//Make a random number
  {
   case 1: pro_A(s);cout<<endl;break;
   case 2: pro_B(s);cout<<endl;break;
   case 3: pro_C(s);cout<<endl;break;
  }
  cout<<"Continue...(y/n)?"<<endl;
  cin>>ch;
  cout<<endl;
  if(ch=='N'||ch=='n')
    break;
 }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -