c语言实现+lru+替换算法
时间: 2023-11-15 10:07:22 浏览: 171
LRU(Least Recently Used)是一种页面置换算法,它会将最近最少使用的页面替换出去。下面是C语言实现LRU替换算法的示例代码:
```c
#include<stdio.h>
#include<stdlib.h>
int main()
{
int frames, pages, counter = 0, time[10], flag1, flag2, i, j, pos, faults = 0;
int frame[10], arr[30];
printf("Enter number of frames: "); scanf("%d", &frames);
printf("Enter number of pages: ");
scanf("%d", &pages);
printf("Enter reference string: ");
for(i = 0; i < pages; ++i){
scanf("%d", &arr[i]);
}
for(i = 0; i < frames; ++i){
frame[i] = -1;
}
for(i = 0; i < pages; ++i){
flag1 = flag2 = 0;
for(j = 0; j < frames; ++j){
if(frame[j] == arr[i]){
counter++;
time[j] = counter;
flag1 = flag2 = 1;
break;
}
}
if(flag1 == 0){
for(j = 0; j < frames; ++j){
if(frame[j] == -1){
counter++;
faults++;
frame[j] = arr[i];
time[j] = counter;
flag2 = 1;
break;
}
}
}
if(flag2 == 0){
pos = findLRU(time, frames);
counter++;
faults++;
frame[pos] = arr[i];
time[pos] = counter;
}
printf("\n");
for(j = 0; j < frames; ++j){
printf("%d\t", frame[j]);
}
}
printf("\n\nTotal Page Faults = %d", faults);
return 0;
}
int findLRU(int time[], int n){
int i, minimum = time[0], pos = 0;
for(i = 1; i < n; ++i){
if(time[i] < minimum){
minimum = time[i];
pos = i;
}
}
return pos;
}
```
阅读全文