1. 程式人生 > >作業系統之頁面置換演算法(最佳置換OPT,先進先出FIFO,最近最久未使用LRU)

作業系統之頁面置換演算法(最佳置換OPT,先進先出FIFO,最近最久未使用LRU)


最近學習作業系統時,實驗要求實現常見的三種頁面置換演算法,博主按照書上要求試著編寫,實現了案例,並記錄在部落格隨記中,以便後續自己複習並也給需要的同學分享參考一下!水平有限,若有錯,請悄悄告訴博主!博主好立即改正。

最佳置換演算法(optimal replacement,OPT)是從記憶體中選擇今後不再訪問的頁面或者在最長一段時間後才需要訪問的頁面進行淘汰。如下例子:

  1 #include <iostream>
  2 #include <stdio.h>
  3 #include <stdlib.h>
  4 #define N 12
  5
#define B 3 6 using namespace std; 7 8 int pageArr[N]={1,2,3,4,1,2,5,1,2,3,4,5};//頁面走向 9 int block[B]={0};//物理塊3個,其數值是頁號 10 typedef struct FLAG { 11 int flags[B]; 12 int counts; 13 } FLAG; 14 15 void opt(int pageArr[],int block[]); 16 int inBlock(int which); 17 int findFar(int next);
18 void Replace(int index,int value); 19 void disPlay(); 20 21 int main(void){ 22 cout << "begin:" <<endl; 23 opt(pageArr,block); 24 cout << "end!" <<endl; 25 return 0; 26 } 27 28 void opt(int pageArr[],int block[]){ 29 int getIndex; 30 for(int
i=0;i<N;i++){ 31 if(i<3){//前3頁號#短缺#進佇列 32 block[i]=pageArr[i]; 33 printf("缺頁:(null)-->%d\n",pageArr[i]); 34 } 35 else { 36 if(i==3){ 37 disPlay(); 38 39 } 40 if(inBlock(pageArr[i])!=-1){//下一個頁面if在物理塊中返回index並跳過,反-1 41 disPlay(); 42 43 continue; 44 } 45 getIndex=findFar(i+1);//從下一個頁號,找到最遠出現的頁面,替換的下標 46 if(getIndex==-1){ 47 cout<<"error,not replace obj!"<<'\t'; 48 } 49 else{ 50 Replace(getIndex,pageArr[i]);//由下標找到上一組替換目標,用第二引數替換 51 disPlay(); 52 53 } 54 } 55 } 56 return; 57 } 58 59 //替換block中的物理塊 60 void Replace(int index,int value){ 61 printf("缺頁:%d--被替換為-->%d\n",block[index],value); 62 block[index]=value; 63 return; 64 } 65 66 67 //找到最遠出現的頁面 68 int findFar(int next){ 69 int index=-1;//error,預設返回不存在的索引 70 FLAG myflag; 71 myflag.flags[0]=0; 72 myflag.flags[1]=0; 73 myflag.flags[2]=0; 74 myflag.counts=0; 75 int stop = N-next; 76 while(stop--){ 77 index=inBlock(pageArr[next++]); 78 if(index!=-1){ 79 myflag.flags[index]=1; 80 myflag.counts++; 81 } 82 else if(myflag.counts==B-1){//有2個不缺值時 83 break; 84 } 85 } 86 for(index=0;index<B;index++){ 87 if(myflag.flags[index]==0) 88 break; 89 } 90 return index; 91 } 92 93 94 //下一個頁面if在物理塊中返回index,反-1 95 int inBlock(int which){ 96 //int i=0; 97 //while(i<B) 98 // if(block[i++]==which) 99 // return i-1; 100 for(int i=0;i<B;i++){ 101 if(block[i]==which) 102 return i; 103 } 104 return -1; 105 } 106 107 //列印一元組 108 void disPlay(){ 109 int i=0; 110 while(i<B){ 111 printf("%d\t",block[i++]); 112 } 113 printf("\n"); 114 return; 115 }

上面是博主使用C++(基本是C語法)編寫的程式碼,執行結果如下:

//////////////////////////////////////////////////////////////////////////

begin:
缺頁:(null)-->1
缺頁:(null)-->2
缺頁:(null)-->3
1 2 3
缺頁:3--被替換為-->4
1 2 4
1 2 4
1 2 4
缺頁:4--被替換為-->5
1 2 5
1 2 5
1 2 5
缺頁:1--被替換為-->3
3 2 5
缺頁:3--被替換為-->4
4 2 5
4 2 5
end!

//////////////////////////////////////////////////////////////////////////