c语言实现三种页面置换算法
时间: 2023-08-13 19:05:31 浏览: 61
好的,这里是三种常见的页面置换算法的C语言实现:
1. 先进先出(FIFO)算法
```c
#include <stdio.h>
#define SIZE 4
int main()
{
int frames[SIZE], pages[SIZE], faults = 0, pointer = 0;
int n, m, flag, i, j;
printf("Enter the number of pages: ");
scanf("%d", &n);
printf("Enter reference string: ");
for (i = 0; i < n; i++)
scanf("%d", &pages[i]);
for (i = 0; i < SIZE; i++)
frames[i] = -1;
for (i = 0; i < n; i++)
{
flag = 0;
for (j = 0; j < SIZE; j++)
{
if (frames[j] == pages[i])
{
flag = 1;
break;
}
}
if (!flag)
{
frames[pointer] = pages[i];
pointer = (pointer + 1) % SIZE;
faults++;
}
printf("\n");
for (j = 0; j < SIZE; j++)
printf("%d\t", frames[j]);
}
printf("\nTotal Page Faults: %d", faults);
return 0;
}
```
2. 最近最少使用(LRU)算法
```c
#include <stdio.h>
#define SIZE 4
int main()
{
int frames[SIZE], pages[SIZE], faults = 0, counter = 0;
int n, m, flag, i, j, k, min;
printf("Enter the number of pages: ");
scanf("%d", &n);
printf("Enter reference string: ");
for (i = 0; i < n; i++)
scanf("%d", &pages[i]);
for (i = 0; i < SIZE; i++)
frames[i] = -1;
for (i = 0; i < n; i++)
{
flag = 0;
for (j = 0; j < SIZE; j++)
{
if (frames[j] == pages[i])
{
flag = 1;
counter++;
break;
}
}
if (!flag)
{
min = 9999;
for (j = 0; j < SIZE; j++)
{
flag = 0;
for (k = i - 1; k >= 0; k--)
{
if (frames[j] == pages[k])
{
flag = 1;
break;
}
}
if (!flag && min > k)
{
min = k;
counter = j;
}
}
frames[counter] = pages[i];
faults++;
}
printf("\n");
for (j = 0; j < SIZE; j++)
printf("%d\t", frames[j]);
}
printf("\nTotal Page Faults: %d", faults);
return 0;
}
```
3. 时钟(Clock)算法
```c
#include <stdio.h>
#define SIZE 4
int main()
{
int frames[SIZE], pages[SIZE], faults = 0, pointer = 0;
int n, m, flag, i, j, used[SIZE] = {0};
printf("Enter the number of pages: ");
scanf("%d", &n);
printf("Enter reference string: ");
for (i = 0; i < n; i++)
scanf("%d", &pages[i]);
for (i = 0; i < SIZE; i++)
frames[i] = -1;
for (i = 0; i < n; i++)
{
flag = 0;
for (j = 0; j < SIZE; j++)
{
if (frames[j] == pages[i])
{
flag = 1;
used[j] = 1;
break;
}
}
if (!flag)
{
while (used[pointer])
{
used[pointer] = 0;
pointer = (pointer + 1) % SIZE;
}
frames[pointer] = pages[i];
used[pointer] = 1;
pointer = (pointer + 1) % SIZE;
faults++;
}
printf("\n");
for (j = 0; j < SIZE; j++)
printf("%d\t", frames[j]);
}
printf("\nTotal Page Faults: %d", faults);
return 0;
}
```
希望能够帮助到你!
阅读全文