假設有10個頁面,n個頁框。頁面的訪問順序為0, 9, 8, 4, 4, 3, 6, 5, 1, 5, 0, 2, 1, 1, 1, 1, 8, 8, 5,
3, 9, 8, 9, 9, 6, 1, 8, 4, 6, 4, 3, 7, 1, 3, 2, 9, 8, 6, 2, 9, 2, 7, 2, 7, 8, 4, 2, 3, 0, 1, 9, 4,
7, 1, 5, 9, 1, 7, 3, 4, 3, 7, 1, 0, 3, 5, 9, 9, 4, 9, 6, 1, 7, 5, 9, 4, 9, 7, 3, 6, 7, 7, 4, 5, 3, 5, 3, 1, 5, 6, 1, 1, 9, 6, 6, 4, 0, 9, 4, 3。
當n在[1,10]中取值時,請編寫程序實現OPT、LRU、FIFO頁面置換算法,並根據頁面訪問順序模擬執行,分別計算缺頁數量。
1.1思路:
-
FIFO:采用隊列存儲,隊列最大容量可變,設為n.
訪問->未找到(缺頁數++)->嘗試將缺頁加入隊列->容量夠則加入隊尾,否則出隊首元素,並將新元素加入隊尾(即順序前移).
-
LRU:鏈表法實現,鏈表最大長度為n
訪問:1.未找到(缺頁數++)->嘗試將缺頁加入鏈表->容量夠則加入鏈表頭,否則淘汰鏈表尾,並加入鏈表頭部
2.找到->將對應鏈表節點提到頭節點.
-
OPT:未來最久不被使用的頁面
訪問->未找到(缺頁數++)->嘗試將缺頁加入頁框->容量夠則加入(數組),否則,計算當前時刻頁框中所有頁面距離下一次使用的時間,取最大的淘汰,並加入新的.
1.2代碼實現:
#include<stdio.h> #include<string.h> #include<stdlib.h> #define tot 100 int schedule[tot] = {0, 9, 8, 4, 4, 3, 6, 5, 1, 5, 0, 2, 1, 1, 1, 1, 8, 8, 5, 3, 9, 8, 9, 9, 6, 1, 8, 4, 6, 4, 3, 7, 1, 3, 2, 9, 8, 6, 2, 9, 2, 7, 2, 7, 8, 4, 2, 3, 0, 1, 9, 4, 7, 1, 5, 9, 1, 7, 3, 4, 3, 7, 1, 0, 3, 5, 9, 9, 4, 9, 6, 1, 7, 5, 9, 4, 9, 7, 3, 6, 7, 7, 4, 5, 3, 5, 3, 1, 5, 6, 1, 1, 9, 6, 6, 4, 0, 9, 4, 3}; int FIFO(int n) { int table[n];//隊列 int head = 0;//隊首 int tail = 0;//隊尾 int sum = 0;//缺頁數 int i, j, k; int flag = 0; for (i = 0; i < tot; i++) { int tar = schedule[i]; flag = 0; for (j = head; j < tail; j++) { if (tar == table[j]) { //找到 flag = 1; break; } } if (!flag) { //沒找到 sum++; if (tail < n) { //未滿,加入隊尾 table[tail++] = tar; } else { for (k = head; k+1 < tail; k++) { table[k] = table[k+1]; //順序前移 } table[tail-1] = tar; } } } return sum; } typedef struct Node{ int order; struct Node * next; }Node, *NPT; int LRU(int n) { Node node[n]; NPT head = NULL, p, r; int i, j, k, cnt = 0; int sum = 0; int flag = 0; for (i = 0; i < tot; i++) { flag = 0; int tar = schedule[i]; r = NULL; p = head; while (p != NULL) { if (p->order == tar) { //找到 flag = 1; break; } r = p; p = p->next; } if (flag) { //找到 if (r == NULL) { //就在頭節點,無需操作 } else { r->next = p->next; p->next = head; head = p; } } else { sum++; p = (NPT) malloc(sizeof(Node)); p->order = tar; p->next = NULL; if (cnt == n) { //容量限制 r = head; if (r->next == NULL) { head = p; } else { while (r->next->next != NULL) { r = r->next; } r->next = NULL; p->next = head; head = p; } } else { p->next = head; head = p; cnt++; } } } return sum; } int OPT(int n) { int table[n]; int cnt = 0, sum = 0; int i, j, k, flag = 0; for (i = 0; i < tot; i++) { int tar = schedule[i]; flag = 0; for (j = 0; j < cnt; j++) { if (table[j] == tar) { flag = 1; break; } } if (flag) { //找到 } else { sum++; if (cnt == n) { //容量滿了 int max = 0; int index = -1; int temp = 0; for (j = 0; j < cnt; j++) { temp = 0; for (k = i + 1; k < tot; k++) { if (table[j] == schedule[k]) { temp++; break; } else temp++; } if (k == tot) { temp = 1000; } if (temp > max) { max = temp; index = j; } } table[index] = tar; } else { table[cnt++] = tar; } } } return sum; } int main(){ int i; for (i = 1; i <= 10; i++) { printf("OPT= %d, FIFO = %d, lru = %d\n",OPT(i), FIFO(i), LRU(i)); } return 0; }