操作系统——模拟时间片轮转调度算法

来源:互联网 发布:重庆seo外包服务价格 编辑:程序博客网 时间:2024/05/16 04:49

按照时间片轮转调度进程

| 动态地输入进程(key,run_time,message),按照输入次序建立就绪队列

l 输入CPU运行的单位时间片(cpu_base_time)

l 按照时间片轮转方式模拟进程逐个被调度并执行单位时间片(运行结束进程结束,否则修改进程运行时间run_time,将该进程放置在就绪队列尾巴)。
(1)假设系统有5个进程,每个进程用一个进程控制块PCB来代表,PCB的格式如右图所示。其中:
进程名:即进程标识。
链接指针:指出下一个到达进程的进程控制块首地址。按照进程到达的顺序排队。系统设置一个队头和队尾指针分别指向第一个和最后一个进程。新生成的进程放队尾。
估计运行时间:可由设计者任意指定一个时间值。
到达时间:进程创建时的系统时间或由用户指定。调度时,总是选择到达时间最早的进程。
进程状态:为简单起见,这里假定进程有两种状态:就绪和完成。并假定进程一创建就处于就绪状态,用R表示。当一个进程运行结束时,就将其置成完成态,用C表示。
(2)为每个进程任意确定一个要求运行时间和到达时间。
(3)按照进程到达的先后顺序排成一个循环队列。再设一个队首指针指向第一个到达进程的首址。
(4)执行处理机调度时,开始选择队首的第一个进程运行。另外再设一个当前运行进程指针,指向当前正运行的进程。
(5)由于本实验是模拟实验,所以对被选中进程并不实际启动运行,而只是执行:
①估计运行时间减1个时间片;
②输出当前运行进程的名字。
用这两个操作来模拟进程的一次运行。

#include <malloc.h>#include <stdio.h>#include <string.h>#define NULL 0typedef struct table {   int key;               /*进程ID号*/   int run_time;         /*进程运行时间*/   char message[10];     /*进程说明信息*/   struct table *next; }node;node *creat(void)      /*定义函数,输入ID号和顺序号,按照输入次序建立进程链表*/{   node *head,*p1,*p2;   int n=0;   p1=p2=(node *)malloc(sizeof(node));   scanf("%d %d %s",&p1->key,&p1->run_time,&p1->message);   head=NULL;   while (p1->run_time>0)    {     n=n+1;         if (n==1) head=p1;     else p2->next=p1;     p2=p1;     p1=(node *) malloc (sizeof(node));   scanf("%d %d %s",&p1->key,&p1->run_time,&p1->message);    }   p2->next=NULL;   return(head);}void print (node *head)  /*输出链表*/  {    node *p;    p=head;   if(!p)   {       printf("该链表为空!");   }   else   {       while(p)       {           printf("%d , ",p->key);           printf("%d , ",p->run_time);           printf("%s",p->message);           p=p->next;           printf("\n");       }   } }node *insert(node *head,node *news)   /*将进程news插入到队列尾部*/  {    node *t;    t=head;    while(t->next)    {        t=t->next;    }    t->next=news;    news->next=NULL;     return head; }node *timeslice(node *head,int cpu_base_time)          /*模拟时间片轮转调度过程:队列首进程使用一个时间片的CPU*/{    node *r,*q;    r=head;    q=(node *)malloc(sizeof(node));    if(r->run_time>cpu_base_time)    {       q->run_time=r->run_time-cpu_base_time;       q->key=r->key;       strcpy(q->message,r->message);       insert(r,q);    }    return head;}void main()  {       int count=0,cpu_base_time;       node *p;       printf("新建的进程控制表为:\nkey run_time message\n");       p=creat();     /*输入进程控制表*/       printf("所建的进程控制表为:\n");       print(p);      /*输出原始进程控制表*/       printf("CPU运行的单位时间片cpu_base_time为:\n");       scanf("%d",&cpu_base_time);       while(p)      /*模拟按单位时间片进程逐个被调度并进入CPU运行的过程*/       {             p=timeslice(p,cpu_base_time);           printf("第%d次被调度的就绪进程:\n",count+1);           printf("key=%d,run_time=%d,message=%s\n",p->key,p->run_time,p->message);           printf("recent table is:\n");           print(p->next);           printf("\n");           count++;           p=p->next;       }   printf("distribute is over!\n");  }