📄 suffle.c
字号:
#include<stdio.h>
#define state_ready 0
#define state_waiting -1
#define state_finish 1
#define resource 10
#define process 4
#define inputfile "in.txt"
#define outputfile "out.txt"
#define maxapply 20
typedef struct pcb
{
int name ;
int state;
int current[resource];
int claim[resource];
int allocation[resource];
int flag;
};
typedef struct application
{
int name;
int number[resource];
int state;
};
struct application apply[maxapply];
struct pcb thepcb[process];
int amount[resource];
int avail[resource];
int napply;
FILE*out;
/*从in.txt中度入资源总量和各个分配请求*/
int initiate()
{
FILE*fp;
int i,j,n;
fp=fopen(inputfile,"r");
for(i=0;i<resource;i++)
{
fscanf(fp," %d",&amount[i]);
avail[i]=amount[i];
}
fscanf(fp," %d",&napply);
for(i=0;i<napply;i++)
{
fscanf(fp," %d",&n);
if(n>=process)
return 1;
apply[i].name=n;
for(j=0;j<resource;j++)
fscanf(fp," %d",&apply[i].number[j]);
apply[i].state=0;
}
for(i=0;i<process;i++)
{
for(j=0;j<resource;j++)
{
thepcb[i].allocation[j]=0;
thepcb[i].current[0]=0;
}
thepcb[i].name=i;
thepcb[i].state=state_ready;
thepcb[i].flag=0;
}
for(i=0;i<napply;i++)
{
n=apply[i].name;
for(j=0;j<resource;j++)
thepcb[n].claim[j]=thepcb[n].claim[j]+apply[i].number[j];
}
for(i=0;i<process;i++)
for(j=0;j<resource;j++)
if(thepcb[i].claim[j]>amount[j])
return 1;
fclose(fp);
return 0;
}
/*把资源请求读入pcb表*/
void readapply(void)
{
int i,j,n;
for(i=0;i<napply;i++)
{
n=apply[i].name;
if(apply[i].state==1)
continue;
if(thepcb[n].state==state_waiting)
continue;
thepcb[n].state=state_waiting;
apply[i].state=1;
for(j=0;j<resource;j++)
thepcb[n].current[j]=apply[i].number[j];
}
}
/*找到以完成的进程,释放资源*/
void checkfinish()
{
int i,k;
for(i=0;i<process;i++)
{
for(k=0;k<resource;k++)
if(thepcb[i].allocation[k]<thepcb[i].claim[k])
break;
if(k==resource)
{
for(k=0;k<resource;k++)
{
avail[k]=avail[k]+thepcb[i].allocation[k];
thepcb[i].allocation[k]=0;
}
thepcb[i].state=state_finish;
fprintf(out,"process %d finished\n",i);
printf("process %d finished\n",i);
}
}
}
int suffle()
{
int i,k;
for(i=0;i<process;i++)
{
if(thepcb[i].state==state_waiting)
{
for(k=0;k<resource;k++)
if(thepcb[i].current[k]>avail[k])
break;
if(k==resource)
{
fprintf(out,"process %d allocated ",i);
printf("process %d allocated ",i);
thepcb[i].state=state_ready;
for(k=0;k<resource;k++)
{
fprintf(out," %d",thepcb[i].current[k]);
printf(" %d",thepcb[i].current[k]);
avail[k]=avail[k]-thepcb[i].current[k];
thepcb[i].current[k]=0;
}
fprintf(out,"\n");
printf("\n");
}
}
}
return 0;
}
int main()
{
int i;
/*banker*/
out=fopen(outputfile,"w");
if(initiate())
return 0;
while(i!=process)
{
readapply();
suffle();
checkfinish();
for(i=0;i<process;i++)
if(thepcb[i].state!=state_finish)
break;
}
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -