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