1. 程式人生 > >作業系統(一):簡單輪轉排程

作業系統(一):簡單輪轉排程

昨天寫作業系統的實驗報告,開始思路很明確,實現起來就碰到麻煩了。花了很多時間去糾正連結串列建立問題,輪轉排程演算法邏輯問題等一系列細節問題。

花了四個多小時去完成程式碼,本來就不擅長程式設計,就只能多花時間了,但真正地做出來覺得再多時間也是值得的。

下面是實驗報告要求及其程式碼:

1、編寫並除錯一個模擬的程序排程程式,採用“輪轉法”排程演算法對五個程序進行排程。五個程序的CPUTime是隨機數產生的,並且計算出每個程序的週轉時間,平均週轉時間。

#include <stdio.h>
#include <stdlib.h> 
#include <time.h> 
#define max 15 //產生隨機數,cpu執行最大時間 
#define min 4 //cpu最小執行時間 

//時間片等於1 
	
int length = 5;
int AllCycling = 0;
int temple=0;

typedef struct pcb
{
	int CPUTime;  //每個程序的執行時間隨機產生 
	int NeedTime; //還需執行多長時間 
	int FinishTime;
	int ID;
	char state;
	struct pcb* next;
}PCB,*PCBList;

//建立程序,且5個程序幾乎同時到達,所以按預設順序排序 
PCBList CreatePCB()
{
	
	PCB *pHead;
	pHead = (PCB*)malloc(sizeof(PCB));
	if(pHead==NULL)
		printf("error!\n");
	pHead->next = NULL;	
	PCB *pTail;		
	pTail = pHead;
	for(int i=0;i<5;i++)
	{
		PCB* p;
		p = (PCB* )malloc(sizeof(PCB));
		if(p==NULL)
			printf("error!\n");
		p->CPUTime = rand()%(max-min+1)+min;

		p->NeedTime = p->CPUTime;
		p->FinishTime = 0;
		p->ID = i;
		p->next = NULL;
		pTail->next = p;
		pTail = p;	
		p->state = 'w';
		 
	}
	pTail->next = NULL;
	
	return pHead;
}

void run(PCB* p)
{
	p->FinishTime = temple;
	p->NeedTime--;
	p->FinishTime++;
	if(p->NeedTime == 0)
	{
		printf("\n");
		printf("程序%d已結束,該程序週轉時間為:%d\n",p->ID,p->FinishTime); 
		temple = p->FinishTime;
		printf("\n");
		p->state = 'f';
		AllCycling = AllCycling+p->FinishTime;	
		length--;				
	}
	else
	{
		temple = p->FinishTime;
		printf("當前排程程序:process %d    CPUTime:%d\n",p->ID,p->CPUTime);	
	}
			
}
int main()
{
	PCB* head,*p;
	head = (PCB*)malloc(sizeof(PCB));
	if(head==NULL)
		printf("error!\n");
	head = CreatePCB();
	p = head->next;
	while(length>0)
	{
		if(p == NULL)
			p = head->next;
		if(p->state=='f')
		{
			while(p->state!='f')
			{
				p = p->next;
			}
		}
		run(p);
		p = p->next;
	}
	
	printf("所有程序已經排程完畢\n");
	printf("平均週轉時間:%d",AllCycling/5); 
	
}

測試資料: