#include <bits/stdc++.h>
#define Max_Time 1e6
using namespace std;
int pcb_num; //进程个数
struct node //定义pcb块
{
char name[10]; //进程名
int arrive_time; //到达时间
int running_time; //运行时间
int finish_time; //完成时间
int wait_time; //周转时间
int circle_time; //周转时间
double p_circle_time; //带权周转时间
struct node *next;
}pcb[100];
void create_pcb(struct node *pcb)
{
cout << "请输入进程个数!" << endl;
cin >> pcb_num;
for(int i = 0; i < pcb_num; i++)
{
cout << "请输入进程名、到达时间、运行时间!" << endl;
//scanf("%s %d %d",pcb[i].name,&pcb[i].arrive_time,&pcb[i].running_time);
cin >> pcb[i].name >> pcb[i].arrive_time >> pcb[i].running_time;
}
}
void FCFS()
{
int curtime = 0; //当前时间
int t[pcb_num]; //创建到达时间副本 用于标记已计算的进程
for(int i = 0; i < pcb_num; i++ ) t[i] = pcb[i].arrive_time;
for(int i = 0; i < pcb_num; i++ )
{
int curfirst = 0; //当前最先到达的进程编号
int minx = t[0];
//找到当前第一个到达的进程,并计算相关时间
for(int j = 1; j < pcb_num; j++ )
if(minx > t[j])
{
minx = t[j];
curfirst = j;
}
t[curfirst] = Max_Time; //标记已计算的进程,防止重复计算
if(curtime < pcb[curfirst].arrive_time) curtime = pcb[curfirst].arrive_time; //如果进程间到达时间不连着 则更新当前时间
pcb[curfirst].wait_time = curtime - pcb[curfirst].arrive_time; //等待时间 = 当前时间 - 到达时间
pcb[curfirst].finish_time = curtime + pcb[curfirst].running_time; //完成时间 = 当前时间 + 运行时间
curtime += pcb[curfirst].running_time;
pcb[curfirst].circle_time = pcb[curfirst].finish_time - pcb[curfirst].arrive_time; //周转时间 = 完成时间 - 到达时间
pcb[curfirst].p_circle_time = (double)pcb[curfirst].circle_time / (double)pcb[curfirst].running_time; //带权周转时间 = 周转时间 / 运行时间
}
}
void print_pcb()
{
cout << "————————————————————————" << endl;
cout << "总进程数为:" << pcb_num << endl;
cout << "当前所有进程如下所示:" << endl;
cout << "进程名 到达时间 运行时间" << endl;
for(int i = 0; i < pcb_num; i ++ )
{
cout << " " <<pcb[i].name << " " << pcb[i].arrive_time << " " << pcb[i].running_time << endl;
}
cout << "————————————————————————" << endl;
}
void print_res()
{
cout << "————————————————————————" << endl;
cout << "进程名 到达时间 运行时间 完成时间 周转时间 带权周转时间" << endl;
for(int i = 0; i < pcb_num; i ++ )
printf(" %s %7d %8d %7d %7d %8.2lf\n",pcb[i].name,pcb[i].arrive_time,pcb[i].running_time,pcb[i].finish_time,pcb[i].circle_time,pcb[i].p_circle_time);
double c_sum = 0,c_avg = 0,pc_sum = 0,pc_avg = 0;
for(int i = 0; i < pcb_num; i ++ )
{
c_sum += pcb[i].circle_time;
pc_sum += pcb[i].p_circle_time;
}
c_avg = c_sum / pcb_num; //平均周转时间
pc_avg = pc_sum / pcb_num; //平均带权周转时间
printf("平均周转时间为:%.2lf,平均带权周转时间为:%.2lf\n",c_avg,pc_avg);
cout << "————————————————————————" << endl;
}
int main() {
create_pcb(pcb); //初始化pcb块
print_pcb(); //打印所有pcb块
FCFS();
print_res(); //打印调度结果
return 0;
}
【操作系统实验】FCFS进程调度实现代码 c++实现
最新推荐文章于 2024-04-01 23:46:46 发布