操作系统 实间片轮转算法 简单实现
#include<iostream>
using namespace std;
#include<windows.h>
#include <iomanip>
typedef struct node{
int x;
char name;
double gettime;
double sertime;
double needtime;
double endtime;
struct node *next;
}Node;
void compute(Node* head,int time);
void myprintf(Node* head,int time);
int main()
{
int num,time;
Node* head=new Node();
Node* p=new Node();
head->next=p;
while(num!=3){
int m=1;
cout<<"1---输入进程---"<<endl;
cout<<"2---进行计算---"<<endl;
cout<<"3---退出程序---"<<endl;
cout<<"请选择:"<<endl;
cin>>num;
switch(num){
case 1:
while(m==1){
system("cls");
cout<<"---请输入进程名-----"<<endl;
cin>>p->name;
p->x=0;
cout<<"---请输入到达时间---"<<endl;
cin>>p->gettime;
cout<<"---请输入服务时间---"<<endl;
cin>>p->sertime;
p->needtime=p->sertime;
Node* pp=new Node();
p->next=pp;
p=p->next;
cout<<endl<<"--是否继续输入进程--"<<endl;
cout<<"1-----是 0-----否"<<endl;
cout<<"请选择:"<<endl;
cin>>m;
}
p=NULL;
break;
case 2:
system("cls");
cout<<"---请输入进程周转时间---"<<endl;
cin>>time;
compute(head,time);
myprintf(head,time);
break;
case 3:
break;
default:
cout<<"输入错误,请重新输入"<<endl;
}
}
}
void myprintf(Node* head,int time)
{
double a=0,b=0;
Node* p=head->next;
system("cls");
cout<<endl<<" 时间片轮转算法,周转时间是"<<time<<endl;
cout<<endl<<" 进程名 ";
while(p->next!=NULL){
cout<<setiosflags(ios::left)<<setw(10)<<p->name;
p=p->next;
}
cout<<"平均"<<endl;
p=head->next;
cout<<" 到达时间 ";
while(p->next!=NULL){
cout<<setiosflags(ios::left)<<setw(10)<<p->gettime;
p=p->next;
}
cout<<endl;
p=head->next;
cout<<" 服务时间 ";
while(p->next!=NULL){
cout<<setiosflags(ios::left)<<setw(10)<<p->needtime;
p=p->next;
}
cout<<endl;
p=head->next;
cout<<" 完成时间 ";
while(p->next!=NULL){
cout<<setiosflags(ios::left)<<setw(10)<<p->endtime;
p=p->next;
}
cout<<endl;
p=head->next;
cout<<" 周转时间 ";
int i=0;
while(p->next!=NULL){
cout<<setiosflags(ios::left)<<setw(10)<<p->endtime-p->gettime;
a+=p->endtime-p->gettime;
i++;
p=p->next;
}
cout<<setiosflags(ios::left)<<setw(10)<<a/i<<endl;
p=head->next;
cout<<" 带权周转时间 ";
i=0;
while(p->next!=NULL){
cout<<setiosflags(ios::left)<<setw(10)<<(p->endtime-p->gettime)/p->needtime;
b+=(p->endtime-p->gettime)/p->needtime;
i++;
p=p->next;
}
cout<<setiosflags(ios::left)<<setw(10)<<b/i<<endl<<endl<<endl;
}
void compute(Node* head,int time)
{
Node *rr=head->next;
while(rr->next!=NULL){
rr->sertime=rr->needtime;
rr=rr->next;
}
int m=0,t=0;
while(m==0){
Node *r=head->next;
while(r->next!=NULL){
if(r->sertime==0)
t-=time;
else if(r->x==0){
if(t>=r->gettime){
r->x=1;
r->sertime-=time;
if(r->sertime<=0){
r->endtime=t+time+r->sertime;
t=t+r->sertime;
r->sertime=0;
}
}
}
else{
r->sertime-=time;
if(r->sertime<=0){
r->endtime=t+time+r->sertime;
t=t+r->sertime;
r->sertime=0;
}
}
t+=time;
r=r->next;
}
m=1;
Node* p=head->next;
while(p->next!=NULL){
if(p->sertime!=0)
m=0;
p=p->next;
}
}
}