//根据“基于动态优先权的时间片轮转”调度算法模拟对进程进行调度
//
#include<stdio.h>
#include<stdlib.h>
//AX 表示 时间片
#define AX 2;
//进程控制块PCB数据结构
struct pcb
{
char name[5]; //进程名
int status; //进程状态
int priority; //进程优先级
int time; //进程要求服务的时间
struct pcb * next; //指向下一进程的指针
};
//创建进程链表(按照优先级由大到小的顺序排列PCB)
/*priority域的值越小,优先级越高 */
struct pcb * order(struct pcb * head,struct pcb * ptr)
{
if(head==NULL)//插入第一个PCB
{
ptr->next=NULL;
return ptr;//返回指向当前头结点的指针
}
else if(head->priority>ptr->priority)//如果头结点priority大于待插入结点priority,待插入结点做头结点
{
ptr->next=head;
return ptr;//返回指向当前头结点的指针
}
else/*如果头结点priority小于待插入结点priority,待插入结点与头结点后的结点比较,
直到它的priority小于某一结点priority,在这一节点前插入待插入结点 */
{
head->next=order(head->next,ptr);//递归调用
return head;//返回指向当前头结点的指针
}
}
//根据基于动态优先权的时间片轮转调度算法进行进程调度
struct pcb * schedule(struct pcb * head)
{
struct pcb * ptr_1=head;
head=ptr_1->next;
//模拟执行优先级最高的进程(已经排好序)
ptr_1->status=1;//将正在执行的进程的状态置为1,运行态
printf(" %s\t ",ptr_1->name);
printf(" %d\t ",ptr_1->priority);
printf(" %d ",ptr_1->time);
printf(" %d\t ",ptr_1->status);
printf("\n");
ptr_1->priority++;//将正在执行的进程的优先级自减1 (值越大,优先级越小)
ptr_1->time=ptr_1->time-AX; //该进程的要求服务时间-时间片
/*在系统分配的时间片内,判断该进程是否执行完毕,若是执行完毕,
销毁该进程记录(从链表中删除,释放其空间);若未完毕,按照其新的优先级,将其加入进程链表 */
if(ptr_1->time>0)
{
ptr_1->status=0; //将该进程进程的状态置为0, 排队等待
head=order(head,ptr_1); //按照其新的优先级,将其加入进程链表
}
else
{
free(ptr_1);//销毁该进程记录(从链表中删除,释放其空间)
}
if(head==NULL) //如果该进程后没有其他进程(该结点后无后继)
{
ptr_1->time=0; //将该进程的要求服务时间置为0
ptr_1->status=0; //将该进程进程的状态置为0,就绪态
}
return(head);
}
//创建进程,并且调用order()函数创建进程链表
struct pcb * creat(int count)
{
int i;
struct pcb * head=NULL;//初始化头指针
struct pcb * pointer_1=NULL;//指向当前创建的PCB
if(count==0||count>10)//进程数最小为1最大为10
{
exit(1);
}
for(i=1;i<=count;i++)
{
//创建进程并分配存储空间,无法分配空间或分配空间出错则异常退出
if((pointer_1=(struct pcb *)malloc(sizeof(struct pcb)))==NULL)
exit(1);
else
{
//输入进程名
printf("Please input the name of the %dth process \n",i);
scanf("%s",&pointer_1->name);
//输入进程动态优先级
printf("Please input the priority of process \n");
scanf("%d",&pointer_1->priority);
//输入进程要求的服务时间
printf("Please input the time of process \n");
scanf("%d",&pointer_1->time);
printf("\n");//进程状态不用输入,运行时置 1,等待时置 0
head=order(head,pointer_1);//将创建的进程块加入到进程链表
}
}
printf("待运行的进程初始状态如下:\n");
printf("name\tpriority\truntime\n");
pointer_1=head;
while(pointer_1!=NULL)
{
printf("%s \t %d \t %d\n",pointer_1->name,pointer_1->priority,pointer_1->time);
pointer_1=pointer_1->next;
}
return head; //返回头指针
}
int main(void)
{
int n; //所要创建的进程个数
struct pcb * head=NULL; //初始化头指针,指向进程链表头结点
//输入想要创建的进程个数
printf("\n\nPlease input number of pocesses you want to build.(n<=10)\n");
scanf("%d",&n);
//创建进程
head=creat(n);
//根据“基于动态优先权的时间片轮转”进程调度算法,模拟进程调度
printf("\n各进程调度运行如下:\n");
printf("status 1:运行; status 0:等待\n\n");
printf(" name\tpriority\truntime\t status");
printf("\n");
while(head!=NULL)
{
head=schedule(head);//根据基于动态优先权的时间片轮转调度算法进行进程调度
}
system("pause");
return(0);
}