c语言实现调度算法--RR算法
测试输入为4个进程,时间片q=3,进程为A、B、C、D,序列号为都为0,运行时间分别为6/7/9/12
RR算法代码实现:
#include<stdio.h>
#define MAX 10
struct task_struct
{
char name[10]; /*进程名称*/
int number; /*进程编号*/
float come_time; /*到达时间*/
float run_begin_time; /*开始运行时间*/
float run_time; /*运行时间*/
float run_end_time; /*运行结束时间*/
int priority; /*优先级*/
int run_flag; /*调度标志*/
int start_flag; //是否为第一次开始调度
} tasks[MAX];
int counter; /*实际进程个数*/
int time_counter=0;
int poutput(); /*调度结果输出*/
int time();
int charge();//判断是否所有的进程都被执行过
void main()
{
pinput();
printf("时间片轮转算法。\n\n");
time();
poutput();
}
int time()
{
float time_temp=0;
int i;
int j=0;
int k=0;
struct task_struct copy_task[MAX];//备份
for(i=0; i<counter; i++)
{
copy_task[j++]=tasks[i];//对进程的初始化信息备份
}
time_temp=tasks[0].come_time;
while(charge())
{
for(i=0; i<counter; i++)
{
if(tasks[i].come_time>time_temp)
{
time_temp=tasks[i].come_time;
}
if(tasks[i].run_flag==0)//该进程还未结束
{
if(tasks[i].start_flag==0) //该条件成立则说明,该进程是第一次执行,记录开始执行时间
{
tasks[i].run_begin_time=time_temp;
tasks[i].start_flag=1;
}
if(tasks[i].run_time/time_counter>1)//至少有两倍的时间片未执行
{
tasks[i].run_time=tasks[i].run_time-time_counter;
time_temp=time_temp+time_counter;
}
else if(tasks[i].run_time-time_counter==0)
{
time_temp=time_temp+time_counter;
tasks[i].run_end_time=time_temp;
tasks[i].run_flag=1;
tasks[i].run_time=copy_task[i].run_time;
}
else//仅剩下不足一倍的时间片
{
time_temp=time_temp+tasks[i].run_time;
tasks[i].run_end_time=time_temp;
tasks[i].run_flag=1;
tasks[i].run_time=copy_task[i].run_time;
}
}
}
}
}
int charge()//判断是否全部进程都执行完毕
{
int k;
int super_flag=0;//判断是否全部的进程都执行完毕
for(k=0; k<counter; k++)
{
if(tasks[k].run_flag==0)
{
super_flag=1;
return super_flag;
break;
}
else
{
super_flag=0;
}
}
return super_flag;
}
int pinput() /*进程参数输入*/
{
int i;
printf("please input the process counter:\n");
scanf("%d",&counter);
printf("please input the length of time:\n");
scanf("%d",&time_counter);
for(i=0; i<counter; i++)
{
printf("******************************************\n");
printf("please input the process of %d th :\n",i+1);
printf("please input the name:\n");
scanf("%s",tasks[i].name);
printf("please input the number:\n");
scanf("%d",&tasks[i].number);
printf("please input the come_time:\n");
scanf("%f",&tasks[i].come_time);
printf("please input the run_time:\n");
scanf("%f",&tasks[i].run_time);
printf("please input the priority:\n");
scanf("%d",&tasks[i].priority);
tasks[i].run_begin_time=0;
tasks[i].run_end_time=0;
tasks[i].run_flag=0; //运行是否结束
tasks[i].start_flag=0;//是否首次被执行
}
return 0;
}
int poutput() /*调度结果输出*/
{
int i;
float turn_round_time=0,f1,w=0;
printf("进程名 进程号 到达时间 运行时间 开始时间 结束时间 优先级 周转时间\n");
for(i=0; i<counter; i++)
{
f1=tasks[i].run_end_time-tasks[i].come_time;
turn_round_time+=f1;
printf("%s\t%d\t%5.3f\t%5.3f\t%5.3f\t %5.3f\t %d\t %5.3f\n",tasks[i].name,tasks[i].number,tasks[i].come_time,tasks[i].run_time,tasks[i].run_begin_time,tasks[i].run_end_time,tasks[i].priority,f1);
}
printf("average_turn_round_timer=%5.2f\n",turn_round_time/counter);
return 0;
}