-
-
Save sumedhahire/9c6d85feed18a7b5eb2609b75f50c793 to your computer and use it in GitHub Desktop.
LRU (Least Recently Used) Page Replacement Algorithm implmentation in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
void lru(int string[20],int n,int size) | |
{ | |
//Creating array for block storage | |
int frames[n]; | |
//Initializing each block with -1 | |
for (int i=0;i<n;i++) | |
frames[i]=-1; | |
int count=0; | |
//Index to insert element | |
int index=-1; | |
//basically it checks which came first past 3 pages so faker gives the address of the first came/least recently used | |
int faker=0; | |
//Counters | |
int page_miss=0; | |
int page_hits=0; | |
//Traversing each symbol in fifo | |
for (int i=0;i<size;i++) | |
{ | |
int flag=0; | |
//To signal if array is full or not | |
int count=0; | |
for(int j=0;j<n;j++) | |
{ | |
if (string[i]==frames[j]) | |
{ | |
flag=1; | |
break; | |
} | |
} | |
if (flag==1) | |
{ | |
page_hits+=1; | |
//if there is a hit then skip the hit and go one ahead | |
faker+2; | |
} | |
else | |
{ | |
for(int j=0;j<n;j++){ | |
if(frames[j]==-1){ | |
count++; | |
} | |
} | |
//Frames are still empty | |
if (count>=0 ) | |
{ | |
index=(index+1)%n; | |
frames[index]=string[i]; | |
page_miss+=1; | |
count--; | |
faker++;//4 | |
} | |
//Frames are full, now we can apply lru | |
else | |
{ | |
for(int j=0;j<n;j++){ | |
if(frames[j]==string[faker-3]){ | |
frames[j]=string[i]; | |
faker++; | |
break; | |
} | |
} | |
} | |
} | |
} | |
printf("\nPage hits: %d",page_hits); | |
printf("\nPage misses: %d",page_miss); | |
} | |
//Main function | |
int main(void) | |
{ | |
int string[]={7,0,1,2,0,3,0,4,2}; | |
int no_frames=3; | |
int size=sizeof(string)/sizeof(int); | |
lru(string,no_frames,size); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment