Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Least Recently Used (LRU) Page Replacement Algorithm
- #include <stdio.h>
- #include <stdbool.h>
- // Function which runs the algorithm and in the end, returns no. of page faults
- int LRU_algorithm(int totalPages, int pages[], int totalFrames, int frames[])
- {
- int i, j, k;
- int pageFaults = 0;
- for (i = 0; i < totalPages; i++)
- {
- int currentPage = pages[i];
- // Check if Page Already Exists
- bool found = false;
- for (j = 0; j < totalFrames; j++)
- {
- if (frames[j] == currentPage)
- {
- found = true;
- break;
- }
- }
- // If Page Already Exists, Page Hit
- if (found == true)
- {
- for (j = 0; j < totalFrames; j++)
- {
- printf("%d \t", frames[j]);
- }
- printf("Page Hit !\n");
- }
- // If Not, Already Frame lo unnavati lo max distance to the left of current page em ochindo adhi replace aitadi
- else
- {
- int maxDistance = -1;
- int indexToBeReplaced;
- // calculate that distance for every frame
- for(j = 0; j < totalFrames; j++)
- {
- int distance = 0;
- for(k = i - 1; k >= 0; k--)
- {
- if(frames[j] != pages[k])
- {
- distance++;
- }
- else
- {
- break;
- }
- }
- if(distance > maxDistance)
- {
- maxDistance = distance;
- indexToBeReplaced = j;
- }
- }
- frames[indexToBeReplaced] = pages[i];
- // Increment Page Faults
- pageFaults++;
- for (j = 0; j < totalFrames; j++)
- {
- printf("%d \t", frames[j]);
- }
- printf("Page Fault !\n");
- }
- }
- return pageFaults;
- }
- int main()
- {
- int totalPages = 19;
- int pages[] = {3, 2, 1, 3, 4, 1, 6, 2, 4, 3, 4, 2, 1, 4, 5, 2, 1, 3, 4};
- int totalFrames = 3;
- int frames[totalFrames];
- int i;
- for (i = 0; i < totalFrames; i++)
- {
- frames[i] = -1;
- }
- printf("Total Number of Page Faults = %d\n", LRU_algorithm(totalPages, pages, totalFrames, frames));
- }
Advertisement
Add Comment
Please, Sign In to add comment