這是課堂實驗題目,當時上課寫的,不算完整,留著做個紀念,若有問題歡迎一起討論。廢話不多說,直接上程式碼:
/***** 時間片輪轉法進行 CPU 調度演算法 ********/
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define N 10 //定義最大進程數
#define TIME 2 //定義時間片大小
typedef struct pcb{
char id[10];//進程標識數
int arrivetime;//到達時間
int runtime;//進程已經占用的cpu時間
int needtime;//進程還需要的時間
char state[12];//進程運行狀態:wait or runing
struct pcb *next;
}pcb,*PCB;
PCB head;//全局變量用來修改就緒隊列
PCB tail;
int count=0;//記錄就緒隊列中進程數
void CreatProcess(){
PCB p,q;
int num;
int i,j;
int arrive[N];
head=tail=(PCB)malloc(sizeof(pcb));
head->next=NULL;
p=head;
printf("輸入你要創建的進程數:");
scanf("%d",&num);
count=num;
printf("********按照進程到達時間從小到大創建就緒隊列******\n");
for(i=1;i<=num;i++){
p->next=(PCB)malloc(sizeof(pcb));
p=p->next;
tail=p;
printf("輸入進程%d的標示符:",i);
scanf("%s",p->id);
printf("輸入進程%d的到達時間:",i);
scanf("%d",&p->arrivetime);
printf("輸入進程%d已占用的cpu時間:",i);
scanf("%d",&p->runtime);
printf("輸入進程%d還需要的cpu時間:",i);
scanf("%d",&p->needtime);
printf("輸入進程%d當前狀態:(run 或者wait):",i);
scanf("%s",p->state);
}
tail->next=p->next=NULL;
}
void RR_RunProcess(){
PCB p,q,temp;
p=head->next;
while(1){
if(head->next==NULL)
{
printf("此時就緒隊列中已無進程!\n");
return ;
}
else
{
while(p){
if((p->needtime>0)&&!(strcmp(p->state,"wait"))){
printf("進程%s開始,\n",p->id );
strcpy(p->state,"run");
p->runtime+=TIME;
p->needtime-=TIME;
if(p->needtime<0)
p->needtime=0;
}
temp=p;
if(temp->needtime>0){
if(count>1){
head->next=temp->next;
tail->next=temp;
tail=tail->next;
strcpy(tail->state,"wait");
tail->next=NULL;
}
else if(count==1){
head->next=temp;
tail=temp;
strcpy(tail->state,"wait");
tail->next=NULL;
}
}
if(temp->needtime==0){
count--;
printf("進程%s結束.\n",p->id);
head->next=temp->next;
free(temp);
}
p=head->next;
}
}
}
}
void main(){
printf("**************進程的初始狀態!**************\n");
CreatProcess();
printf("*******************************************\n\t\t程序運行結果如下:\n\n");
printf("*******************************************\n");
RR_RunProcess();
}
運行結果如下附件:
整體思路是:用鏈表維護就緒隊列,每個時間片讓隊首進程執行 TIME 個單位,若尚未完成則移到隊尾重新排隊,若已完成則從隊列移除並釋放記憶體,直到就緒隊列清空為止,以此模擬 Round Robin 的輪轉過程。