时间片轮转调度算法(C++代码)

来源:互联网 发布:centos 6.5mysql 编辑:程序博客网 时间:2024/05/01 23:23

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream.h>

typedef struct node
{
 char name[10];    
 int prio;         
 int round;        
 int cputime;      
 int needtime;     
 int count;        
 char state;       
 struct node *next;
}PCB;
PCB *finish,*ready,*tail,*run; //队列指针
int N;     //进程数

void firstin()
{
 run=ready;      //就绪队列头指针赋值给运行头指针
 run->state='R'; //进程状态变为运行态]
 ready=ready->next; //就绪队列头指针后移到下一进程
}
//输出标题函数
void prt1(char a)
{
 if(toupper(a)=='P')  //优先级法
  cout<<" "<<endl;
 cout<<"进程名 占用CPU时间 到完成还要的时间 轮转时间片 状态"<<endl;
}

//进程PCB输出
void prt2(char a,PCB *q)
{
 if(toupper(a)=='P')  //优先级法的输出
  cout<<q->name<<"       "<<q->cputime<<"           "<<q->needtime<<"               "<<
  q->round<<"         "<<q->state<<endl;
}

//输出函数
void prt(char algo)
{
 PCB *p;
 prt1(algo);  //输出标题
 if(run!=NULL)  //如果运行指针不空
  prt2(algo,run);  //输出当前正在运行的PCB
 p=ready;  //输出就绪队列PCB
 while(p!=NULL)
 {
  prt2(algo,p);
  p=p->next;
 }
 p=finish;   //输出完成队列的PCB
 while(p!=NULL)
 {
  prt2(algo,p);
  p=p->next;
 }
 getchar();  //按住任意键继续
}

//时间片轮转的插入算法
void insert(PCB *q)
{
 PCB *p1,*s,*r;
 s=q;  //待插入的PCB指针
 p1=ready;  //就绪队列头指针
 r=p1;  //*r做pl的前驱指针
 while(p1!=NULL)
  if(p1->round<=s->round)
  {
   r=p1;
   p1=p1->next;
  }
  if(r!=p1)
  {
   r->next=s;
   s->next=p1;
  }
  else
  {
   s->next=p1;  //否则插入在就绪队列的头
   ready=s;
  }
}

//优先级创建初
void create(char alg)
{
 PCB *p;
 int i,time;
 char na[10];
 ready=NULL; 
 finish=NULL;
 run=NULL;   
 cout<<"输入进程名及其需要运行的时间:"<<endl;
 for(i=1;i<=N;i++)
 {
  p=new PCB;
  cin>>na;
  cin>>time;
  strcpy(p->name,na);
  p->cputime=0;
  p->needtime=time;
  p->state='W';
 
  p->round=0;
  if(ready!=NULL) 
   insert(p);
  else
  {
   p->next=ready; 
   ready=p;
  }
  cout<<"输入进程名及其需要运行的时间:"<<endl;
 }
 prt(alg); 
 run=ready; 
 ready=ready->next;
 run->state='R';
}


void timeslicecycle(char alg)
{
 while(run!=NULL)
 {
  run->cputime=run->cputime+8;
  run->needtime=run->needtime-8;
  run->round=run->round+8;
  if(run->needtime<=0)
  {
   run->next=finish;
   finish=run;
   run->state='F';
   run=NULL;
   if(ready!=NULL)
    firstin();
  }
  else
  {
   run->state='W';
   insert(run);
   firstin();
  }
  prt(alg);
 }
}


//主函数
void main()
{
 char algo='P';  //算法标记
 cout<<"输入进程的个数:";
 cin>>N;  //输入进程数
 create(algo);  //创建进程
 timeslicecycle(algo);  //优先级法调度
} //main() 

 

注:这个程序不好之处是时间片不是由键盘输入,还有就是会出现—状态,请大家更正,要是需要的话。

原创粉丝点击