Least Recently Used(LRU) Page Replacement algorithm
Least Recently Used(LRU) Page Replacement algorithm:
Program Description:
The Least Recently Used replacement policy chooses to replace the
page which has not been referenced for the longest time.
The
operating system keeps track of when each page was referenced by
recording the time of reference or by maintaining a stack of references.This policy
assumes the recent past will approximate the immediate future.
Program Code:
#include<stdio.h>
#include<conio.h>
int main()
{
int cnt[10],page[20],frame[10];
int page_fault=0,t1,t2,i,t=0,j,k,m=0,n=0,min,count=0,nop,frame_size;//nop-->no. of pages
clrscr();
printf("Enter the no.of pages:\t");
scanf("%d",&nop);
printf("Enter the size of frame:\t");
scanf("%d",&frame_size);
printf("Enter page sequence:\n");
for(i=0;i<nop;i++)
scanf("%d",&page[i]);
for(i=0;i<frame_size;i++)
{
frame[i]=0;cnt[i]=0; //initialize frame to zero
}
k=0;
for(i=0;i<nop;i++)
{
m=0;
for(j=0;j<frame_size;j++)
cnt[j]=0;
for(j=0;j<frame_size;j++)
{
if(frame[j]==page[i])
{
m++;
}
}
if(m!=0)
{
count++;
if(k>2)
k=0;
k=k+1;
printf("page %d\t",page[i]);
printf(" frame\t");
for(j=0;j<frame_size;j++)
printf(" %d",frame[j]);
printf("\tNo page fault\t");
printf("\tPage_fault till now:\t%d\n",page_fault);
}
else if(count>3)
{
for(j=0;j<frame_size;j++)
{
t2=(count-3);
for(n=(count-1);n>t2;n--)
{
if(frame[j]==page[n])
{ cnt[j]++;
}
}
}
for(j=0;j<3;j++)
min=cnt[0];
t=0;
for(j=0;j<frame_size;j++)
{
if(cnt[j]<min)
{ min=cnt[j];
t=j;
}
}
if(k>2)
k=0;
frame[t]=page[i];
count++;
k++;
printf("page %d\t",page[i]);
printf(" frame\t");
for(j=0;j<frame_size;j++)
printf(" %d",frame[j]);
page_fault++;
printf("\tpage fault occurs\t");
printf("Page_fault till now:\t%d\n",page_fault);
}
else
{ if(k>2)
{ k=0;}
frame[k]=page[i];
count++;
k++;
printf("page %d\t",page[i]);
printf(" frame\t");
for(j=0;j<frame_size;j++)
printf(" %d",frame[j]);
page_fault++;
printf("\tpage fault occurs\t");
printf("Page_fault till now:\t%d\n",page_fault);
}
}
getch();
return 0;
}
Output:
No comments:
Post a Comment