时间片轮转(RR)调度算法
时间片轮转(RR)调度算法是专门为分时系统设计的。它类似于FCFS调度,但是增加了抢占以切换进程。该算法中,将一个较小时间单元定义为时间量或时间片,时间片的大小通常为 10~100ms。就绪队列作为循环队列,CPU 调度程序循环整个就绪队列,为每个进程分配不超过一个时间片的 CPU。为了实现 RR 调度,我们再次将就绪队列视为进程的 FIFO 队列。新进程添加到就绪队列的尾部。CPU调度程序从就绪队列中选择第一个进程,将定时器设置在一个时间片后中断,最后分派这个进程。
流程图如下所示:
#include "string.h"
#include "stdio.h"
#define NULL 0
typedef struct quen
{
char pname[8];
int time1;
int time2;
char state;
struct quen *next;
}QUEN;
void main()
{
QUEN *q, *p, *head, *m;
char str[8],f;
int t,d,n;
printf("Enter the maxnumber of nodes (n): \ n");
scanf ("%d", &n);
d=n;
if (d> 0)
{
printf ("enter the pname:");
scanf ("%s", str);
printf("enter the need time:");
scanf("%d",&t);
head=p=(QUEN*)malloc(sizeof(QUEN));
strcpy(p->pname,str);
p->time1=t;
p->time2=0;
p->state='R';
p->next=NULL;
head=p;
getchar();
--d;
}
while(d>0)
{
printf ("enter the pname:");
scanf ("%s", str);
printf ("enter need time:");
scanf ("%d", & t);
q= (QUEN *) malloc (sizeof (QUEN));
strcpy (q-> pname, str); q-> time1=t;
q-> time2=0;
q->state='R';
q->next=NULL;
p->next=q;
p=q;
--d;
p->next=head;
q=head;
}
printf("process name need time runned static\n");
do
{
printf("%s %d %d %c\n",q->pname,q->time1,q->time2,q->state);
q=q->next;
}while(q!=head);
printf("\n");
do
{
if(head->time2<head->time1)
{
head->time2++;
if(head->time2==head->time1)
{
head->state='E';
q=head;
printf("The running process is %s\n",q->pname);
printf("process name left time runned static \n");
do
{
printf ("%s %d %d %c \n", q-> pname, q-> time1, q-> time2, q-> state);
q=q-> next;
}while (q!=head);
printf("\n");
head=head->next;
q=head;
p->next=head;
}else
{
printf("The running process is %s\n",q->pname);
printf("process name left time runned static\n");
do
{
printf("%s %d %d %c\n",q->pname,q->time1,q->time2,q->state);
q=q->next;
}while(q!=head);
printf("\n");
head=head->next;
q=head;
p=p->next;
}
printf("Is it needing new process?(y or n) \n ");
getchar();
scanf ("%c" ,&f);
if(f=='Y'||f=='y')
{
getchar();
printf("Enter the new pname:");
scanf("%s",str);
printf("Enter the new neededtime:");
scanf("%d",&t); m=(QUEN *)malloc(sizeof(QUEN));
strcpy(m->pname,str);
m->time1=t; m->time2=0;
m->state='R';
m->next=NULL;
if(q->next->state=='E')
{
p=m;
head=m;
p->next=head;
q=head;
}
else
{
p->next=m;
m->next=head;
p=m;
}
}
}
}while(q->next->state!='E');
printf("The processes are finished\n");
}