#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define randomize() srand((unsigned)time(NULL)) //定义一个宏
//PCB结构体定义部分
typedef struct PCB
{
/** 进程标识符,取值1-5 **/
unsigned int id;
/** 进程优先级,随机产生,值1-5 **/
signed int priority;
/**
目前已占用的CPU时间数,
初值为0;当该进程被调
用执行时,每执行一个时
间片,Used加1
**/
unsigned int used;
/**
进程尚需的CPU时间数,初值表示
该进程需要运行的总时间,取值
范围为5—10。并随机产生,每运
行一个时间片need减1;need为0则
进程结束。
**/
unsigned int need;
/**
进程状态R(运行),W(就绪),F(完成);
初始时都处于就绪状态
**/
unsigned char status;
/**
指向就绪队列中下一个进程的PCB的指针
**/
struct PCB *next;
};
//程序入口主函数
int main(void)
{
struct PCB process[5];
int i=0;
for(i;i<5;i++)
{
//初始化进程ID
process[i].id = i+1;
//初始化进程优先级
process[i].priority = rand()%5+1;
//初绐化已占用时间数
process[i].used = 0;
//初始化还要时间数(5-10)
process[i].need = rand()%5+6;
//初始化进程状态(就绪)
process[i].status = 'W';
//初始化指向下一个PCB的指针
process[i].next = NULL;
printf("process[%d]: id = %d",i+1,process[i].id);
printf(" priority = %d",process[i].priority);
printf(" used = %d",process[i].used);
printf(" need = %d",process[i].need);
printf(" status = %c",process[i].status);
printf(" next = %s",process[i].next);
printf("\n");
}
randomize();
//形成一个按进程优先级从大到小排列的队列
int j = 0;
int k = 1;
for(j;j<5;j++)
{
struct PCB temp;
for(k=j+1;k<5;k++)
{
if(process[j].priority<process[k].priority)
{
temp = process[j];
process[j] = process[k];
process[k] = temp;
}
}
}
printf("排序结果为:");
for(i=0;i<4;i++)
{
printf(" %d ",process[i].priority);
process[i].next = &process[i+1];
}
//初始化head,tail指针
struct PCB *head = &process[0];
struct PCB *tail = &process[4];
struct PCB *run = head;
tail->next = NULL;
printf("\n初始化head,tail指针:");
printf("head: %d ",head->priority);
printf("tail: %d \n",(*tail).priority);
printf("\n--------准备完成,开始调度---------\n");
while(head!=NULL)
{
if(head == NULL)
break;
else
run = head;
run->priority--;
run->status='R';
run->used ++ ;
if(run->need>0)
run ->need -- ;
head = head->next;
printf("当前正在执行的进程ID:%d,status:%c,priority:%d,used:%d,need:%d\n"
,run->id,run->status,run->priority,run->used,run->need);
printf("时间片:");
for(i=0;i<15000;i++)
{
int a=50000;
while(a--);
if(i%500==0)
printf("#");
}
if(run->need > 0)
{
printf(" 进入就绪队列\n");
if(head->next == NULL)
head = run;
else
{
run->status='W';
struct PCB *temp = head;
struct PCB *pre = head;
int flag = 1;
while(flag)
{
if(temp!=tail && temp->priority < run->priority)
{
run->next = temp;
pre->next = run;
flag = 0;
}
if(temp==tail)
{
run->next = NULL;
tail->next = run;
tail = tail->next;
flag = 0;
}
else
{
pre = temp;
temp = temp->next;
}
}
}
}
else
printf(" 完成\n");
printf("\n");
}
return 0;
}
用C模拟进程调度
最新推荐文章于 2022-06-10 19:39:27 发布