#include<conio.h>
#include<iostream.h>
#include<fstream.h>
#define N 20
typedef struct pcb/*进程控制块定义*/
{
char pname[N]; /*进程名*/
int runtime; /*运行时间*/
int arrivetime; /*到达时间*/
char state; /*进程状态*/
struct pcb *next; /*链接指针*/
}PCB;
PCB head_input;//就绪队列
PCB head_run;
PCB * pcb_input;
static char R='r',C='c';
unsigned long current; /*记录系统当前时间的变量*/
void inputprocess(); /*建立进程函数*/
int readyprocess(); /*建立就绪队列函数*/
int readydata(); /*判断进程是否就绪函数*/
int runprocess(); /*运行进程函数*/
ofstream fout;
/*定义建立就绪队列函数*/
int readyprocess()
{
while(1)
{
if(readydata()==0)/*判断是否就绪函数*/
return 1;
else
runprocess();/*运行进程函数*/
}
}
/*定义判断就绪队列是否有进程函数*/
int readydata()
{
if(head_input.next==NULL)
{
if(head_run.next==NULL)
return 0;//就绪队列和运行队列都没有进程时,返回0,最终程序结束
else
return 1;//就绪队列为空,运行队列非空,返回上级循环,继续运行
}
PCB *p1,*p2,*p3;
p1=head_run.next;
p2=&head_run;
while(p1!=NULL)
{
p2=p1;
p1=p2->next;
}
p1=p2;//p1指向run队列的最后一个进程
p3=head_input.next;//p3指向就绪队列的第一个进程
p2=&head_input;
while(p3!=NULL)
{//遍历就绪队列
if(((unsigned long)p3->arrivetime<=current)&&(p3->state==R))
{//若符合条件(p3所指进程的时间)
cout<<"Time slice is "<<current<<" (time "<<(current+500)/1000<<"); Process "<<p3->pname<<" start,\n";
fout<<"Time slice is "<<current<<" (time "<<(current+500)/1000<<"); Process "<<p3->pname<<" start,\n";
p2->next=p3->next;
//将p3所指进程,放到p1所指进程之后
p3->next=p1->next;
p1->next=p3;
p3=p2;
}
p2=p3;
p3=p3->next;
}
return 1;
}
/*定义运行进程函数*/
int runprocess()
{
PCB *p1,*p2;
if(head_run.next==NULL)
{//若运行队列为空,时间+1,跳出函数
current++;
return 1;
}
else
{
p1=head_run.next;//p1指向运行队列的第一个进程
p2=&head_run;
while(p1!=NULL)
{//遍历运行队列
p1->runtime--;//p1所指进程运行时间-1
current++;//时间+1
if(p1->runtime<=0)
{//p1所指进程运行时间=0,输出并删除
cout<<"Time slice is "<<current<<" (time "<<(current+500)/1000<<"); Process "<<p1->pname<<" end. \n";
fout<<"Time slice is "<<current<<" (time "<<(current+500)/1000<<"); Process "<<p1->pname<<" end. \n";
p1->state=C;
p2->next=p1->next;
delete p1;
p1=NULL;
}
else
{
p2=p1;
p1=p2->next;
}
}
return 1;
}
}
/*定义建立进程函数*/
void inputprocess()
{
PCB *p1,*p2;
int num; /*要建立的进程数*/
unsigned long max=0;
cout<<"How many processes do you want to run:";
fout<<"How mant processes do you want to run:";
cin>>num;
fout<<num<<endl;
p1=&head_input;
p2=p1;
p1->next=new PCB;
p1=p1->next;
for(int i=0;i<num;i++)
{
cout<<"No."<<i+1<<" process input pname:";
fout<<"No."<<i+1<<" process input pname:";
cin>>p1->pname;
fout<<p1->pname<<endl;
cout<<" runtime:";
fout<<" runtime:";
cin>>p1->runtime;
fout<<p1->runtime<<endl;
cout<<" arrivetime:";
fout<<" arrivetime:";
cin>>p1->arrivetime;
fout<<p1->arrivetime<<endl;
p1->runtime=(p1->runtime)*1000;
p1->arrivetime=(p1->arrivetime)*1000;
p1->state=R;
if((unsigned long)(p1->arrivetime)>max)
max=p1->arrivetime;
p1->next=new PCB;
p2=p1;
p1=p1->next;
}
delete p1;
p1=NULL;
p2->next=NULL;
}
void main()
{
fout.open("result.txt");
cout<<"\ntime 1=1000 time slice\n";
fout<<"\ntime 1=1000 time slice\n";
current=0;
inputprocess();
readyprocess();
cout<<flush;
getch();
fout.close();
}
回复 更多评论