?? 128.cpp
字號:
#include<stdafx.h>
#include<iostream.h>
#include<stdlib.h>
#include<windows.h>
#define RES_TYPES 4
#define PROCESS_NUM 6
int available[RES_TYPES]={4,4,4,4};
int max_requ[PROCESS_NUM ][RES_TYPES ] ={{1,2,3,2},{2,1,2,1},{1,1,1,1},{2,1,1,1},{1,2,1,0},{1,0,1,1}};
int requ_seq[PROCESS_NUM][100]={{8,1,2,2,3,3,3,4,4},{6,1,2,3,4,1,3},{4,3,4,1,2},{5,4,3,2,1,1},{4,2,2,3,1},{3,1,4,3}};
int requ_resource(int res_idx,int num);
void release_resource(int res_idx,int num);
int process_point[PROCESS_NUM]={1,1,1,1,1,1};
int process_completed[PROCESS_NUM]={1,1,1,1,1,1};
int resource_alloc[PROCESS_NUM][RES_TYPES]={{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}};
int resource_need[PROCESS_NUM][RES_TYPES]={{1,2,3,2},{2,1,2,1},{1,1,1,1},{2,1,1,1},{1,2,1,0},{1,0,1,1}};
int *k;
int a[RES_TYPES];
int exist_uncompleted_process()
{
Sleep(rand()%1000);
int i,j;
j=0;
for(i=0;i<6;i++)
{
if(*(process_completed+i)==0)
j++;
}
if(j==6) return 0;
else return 1;
}
int get_uncompleted_process_id()
{
int p;
//Sleep(rand()%10);
p=rand()%6;
while(*(process_completed+p)!=1)
{
p=rand()%6;
}
if(*(process_completed+p)==1)
return p;
}
int pre_alloc(int i,int j)
{
int m,b,p;
p=0;
for(b=*k;b<=requ_seq[i][0];b++)
{
m=requ_seq[i][b];
if(*(available+m-1)>0)
{
*(available+m-1)=*(available+m-1)-1;
p++;
}
else return 0;
}
if(p==(requ_seq[i][0]-*k+1))
return 1;
}
void alloc(int i,int j)
{
int d;
for(d=0;d<4;d++)
{
*(available+d)=*(a+d);
}
*(available+j-1)=*(available+j-1)-1;
}
void release_resource(int res_idx,int num)
{
*(available+res_idx-1)=*(available+res_idx-1)+1;
}
int main()
{
int i,j,w;
int n,s,r,t;
int c[6][4];
while(exist_uncompleted_process())
{
Sleep(rand()%500);
i=get_uncompleted_process_id();
k=&process_point[i];
j=requ_seq[i][*k];
for(w=0;w<4;w++)
{
*(a+w)=*(available+w);
}
if(pre_alloc(i,j))
{
alloc(i,j);
*(*(resource_alloc+i)+j-1)=*(*(resource_alloc+i)+j-1)+1;
for(n=0;n<6;n++)
{
c[i][n]=max_requ[i][n]-resource_alloc[i][n];
}
cout<<"進程"<<i+1;
cout<<"得到資源數(shù)"<<resource_alloc[i][0]<<" ";
cout<<resource_alloc[i][1]<<" ";
cout<<resource_alloc[i][2]<<" ";
cout<<resource_alloc[i][3]<<" "<<endl;
cout<<"進程"<<i+1<<"尚需資源數(shù)"<<c[i][0]<<" ";
cout<<c[i][1]<<" ";
cout<<c[i][2]<<" ";
cout<<c[i][3]<<endl;
cout<<endl;
if(process_point[i]==requ_seq[i][0])
{
*(process_completed+i)=0;
for(r=1;r<requ_seq[i][0];r++)
{
s=requ_seq[i][r];
release_resource(s,1);
*(*(resource_alloc+i)+s-1)=*(*(resource_alloc+i)+s-1)-1;
}
cout<<"進程"<<i+1<<"已經(jīng)執(zhí)行完畢"<<endl;
cout<<endl;
}
for(t=0;t<6;t++)
{
if(*(process_completed+t)==2)
*(process_completed+t)=1;
}
Sleep(rand()%500);
process_point[i]++;
}
else *(process_completed+i)=2;
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -