操作系統中的最佳置換Optimal算法的實現(java實現)

在學習操作系統這本書的時候,我們使用的是湯小丹老師的《計算機操作系統》接下來我將會使用java語言去實現內部代碼。

Swap指令

最佳置換算法是由Belady於1966年提出的一種理論上的算法。其所選擇的被淘汰頁面是以後永不使用的,或許是在最長(未來)時間內不再被訪問的頁面。採用最佳置換算法通常保證獲取最低的缺頁率。但人們目前還無法與之,一個線程在內存的若干個頁面中,哪個頁面是未來最長時間內不再被訪問的,因此該算法是無法實現的,但是可以利用該算法去評價其他算法。現在就說明如下。

假定系統爲某進程分配了三個物理塊,並考慮有以下的頁面號引用串:

7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1

進程運行時,先將7,0,1三個頁面裝在內存,以後需要訪問頁面2時,將產生缺頁中斷。此時OS將根據最佳算法置換算法將選擇頁面7予以淘汰。這是因爲頁面0將作爲第五個被訪問的頁面,頁面1爲第十四個被訪問的頁面,而頁面7則是要在低18次訪問才需要引入,以此類推。

以下是源代碼實現部分:

package chapter02;

public class P175Optimal {
    //查找數組中是否存在並且未存儲元素的索引
    public static int existEmpty(int[] place){
        for (int i = 0; i < place.length; i++) {
            if(place[i]==-1)
                return i;
        }
        //不爲空
        return -1;
    }

    //查找元素是否在數組中存在
    public static boolean paramExist(int[] place,int param){
        for (int i = 0; i < place.length; i++) {
            if(place[i]==param)
                return true;
        }
        //不爲空
        return false;
    }

    //獲取最大距離值
    public static int getMaxIndexOfNeed(int[] place,int[] block,int start){
        //最近需求定位
        int minBlockIndex = -1;
        int minPlaceIndex = -1;
        for(int PlaceIndex = 0;PlaceIndex<place.length;PlaceIndex++){
            for (int BlockIndex = start + 1; BlockIndex < block.length; BlockIndex++) {
                if (block[BlockIndex] == place[PlaceIndex]) {
                    if (minBlockIndex < BlockIndex) {
                        minBlockIndex = BlockIndex;
                        minPlaceIndex = PlaceIndex;
                    }
                    break;
                }
                //這操作是查找獲取最大距離值的時,發現內存中的元素以後永久不使用的元素時候
                if(BlockIndex==block.length-1 && block[BlockIndex]!=place[PlaceIndex]){
                    return PlaceIndex;
                }
            }
        }
        return minPlaceIndex;
    }
    public static void main(String[] args) {
        int[] block = new int[]{7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1};
        int[] place = new int[]{-1, -1, -1};
        for (int index = 0; index < block.length; index++) {
            //假設元素存在則不需要進行任何操作
            if(paramExist(place,block[index])){
                continue;
            }else {
                int emptyIndex = existEmpty(place);
                //當前已經元素滿了
                if(emptyIndex==-1){
                    int maxIndex = getMaxIndexOfNeed(place,block,index);
                    place[maxIndex] = block[index];
                    for (int param : place) {
                        System.out.print(param + " ");
                    }
                    System.out.println();
                }else{
                    place[emptyIndex] = block[index];

                }
            }
        }
    }
}

實驗結果:

"C:\Program Files\Java\jdk1.8.0_101\bin\java.exe" 
2 0 1 
2 0 3 
2 4 3 
2 0 3 
2 0 1 
7 0 1 

實驗結果與上結果一致。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章