优先调度算法
#include<iomanip.h>#include<fstream.h>
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
class pcb
{
public:
char name[10]; /*进程标志名*/
int setno; /*优先数*/
int needtime; /*进程所需时间*/
char S[3][10];
void value(){strcpy(S[0],"就绪");strcpy(S[1],"运行");strcpy(S[2],"完成");} /*进程状态*/
}p[5];
void main()
{
char n[5][10];
int N[5];
int t[5];
int i,j,k,l;
char m[10];
loop:
cout<<"请分别输出各个进程标志名,优先数和所需时间"<<endl;
for(i=0;i<5;i++)
{
cout<<"进程"<<i+1<<":"<<endl;
cout<<"标志名:";cin>>n[i];
cout<<"优先数:";cin>>N[i];
cout<<"所需时间:";cin>>t[i];
cout<<endl;
strcpy(p[i].name,n[i]);p[i].setno=N[i];p[i].needtime=t[i];
}
for(i=0;i<5;i++)
{
if((p[i].setno<=0)||(p[i].needtime<=0))
{
cout<<"优先数或所需时间初始值应大于0,请重新输入!"<<endl<<endl;
goto loop;
}
}
cout<<"按优先大小排列如下:"<<endl;
cout<<"进程"<<" 标志名"<<" 优先数"<<" 所需时间"<<endl;
for(i=0;i<5;i++)
{
for(j=i;j<5;j++)
{
if(p[i].setno<=p[j].setno)
{
strcpy(m,p[i].name);k=p[i].setno;l=p[i].needtime;
strcpy(p[i].name,p[j].name);p[i].setno=p[j].setno;p[i].needtime=p[j].needtime;
strcpy(p[j].name,m);p[j].setno=k;p[j].needtime=l;
}
}
cout<<"进程"<<i+1<<" "<<setw(6)<<p[i].name<<setw(8)<<p[i].setno<<setw(10)<<p[i].needtime<<endl;
}
int num=5;
int h,score=0;
do
{
cout<<"优先数最大的进程首先运行,优先数减3,所需时间减1!"<<endl;
getch();
cout<<"进程状态:"<<endl;
p[0].needtime=p[0].needtime-1;p[0].setno=p[0].setno-3;
for(i=0;i<num;i++)
{
if((p[i].needtime<=0)||(p[i].setno<=0))
{
if(p[i].setno<=0)
{
cout<<"因为进程"<<i+1<<"优先级数小于等于0,系统默认为该进程完成";
if(i==0)
{
for(i=0;i<num-1;i++)
{
strcpy(p[i].name,p[i+1].name);p[i].setno=p[i+1].setno;p[i].needtime=p[i+1].needtime;
}
}
else if(i>0&&i<num-1)
{
for(h=i;h<num;h++)
{
strcpy(p[h].name,p[h+1].name);p[h].setno=p[h+1].setno;p[h].needtime=p[h+1].needtime;
}
}
}
else if(p[i].needtime<=0)
{
cout<<"进程"<<i+1<<"完成 ";
if(i==0)
{
for(i=0;i<num-1;i++)
{
strcpy(p[i].name,p[i+1].name);p[i].setno=p[i+1].setno;p[i].needtime=p[i+1].needtime;
}
}
else if(i>0&&i<num-1)
{
for(h=i;h<num;h++)
{
strcpy(p[h].name,p[h+1].name);p[h].setno=p[h+1].setno;p[h].needtime=p[h+1].needtime;
}
}
}
num=num-1;
score=score+1;
}
else if((p[i].needtime!=0)&&(i==0))
{
cout<<"进程"<<i+1<<"运行 ";
}
else
cout<<"进程"<<i+1<<"就绪 ";
}
cout<<endl;
getch();
if(score==5) break;
cout<<"重新按进程大小排列:"<<endl;
cout<<"进程"<<" 标志名"<<" 优先数"<<" 所需时间"<<endl;
for(i=0;i<num;i++)
{
for(j=i;j<num;j++)
{
if(p[i].setno<=p[j].setno)
{
strcpy(m,p[i].name);k=p[i].setno;l=p[i].needtime;
strcpy(p[i].name,p[j].name);p[i].setno=p[j].setno;p[i].needtime=p[j].needtime;
strcpy(p[j].name,m);p[j].setno=k;p[j].needtime=l;
}
}
cout<<"进程"<<i+1<<" "<<setw(6)<<p[i].name<<setw(8)<<p[i].setno<<setw(10)<<p[i].needtime<<endl;
}
}while(score!=5);
cout<<"所有进程都已经完成,请按任意键退出!"<<endl;
getch();
}