Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Lab10:Least Recently Used (LRU) Page

Replacement algorithm
In operating systems that use paging for memory management, page replacement algorithm are
needed to decide which page needed to be replaced when new page comes in. Whenever a new
page is referred and not present in memory, page fault occurs and Operating System replaces
one of the existing pages with newly needed page. Different page replacement algorithms
suggest different ways to decide which page to replace. The target for all algorithms is to
reduce number of page faults.
In Least Recently Used (LRU) algorithm is a Greedy algorithm where the page to be replaced
is least recently used. The idea is based on locality of reference, the least recently used page is
not likely
Let say the page reference string 7 0 1 2 0 3 0 4 2 3 0 3 2 . Initially we have 4 page slots empty.
Initially all slots are empty, so when 7 0 1 2 are allocated to the empty slots —> 4 Page faults
0 is already their so —> 0 Page fault.
when 3 came it will take the place of 7 because it is least recently used —>1 Page fault
0 is already in memory so —> 0 Page fault.
4 will takes place of 1 —> 1 Page Fault
Now for the further page reference string —> 0 Page fault because they are already available
in the memory.

CODE :-
#include<iostream>
using namespace std;
struct node
{
char data;
node *next;
};
class lru_alg
{
char ref[100];
int frame,count,fault;
node *front,*rear;
public:
lru_alg()
{
front=rear=NULL;
fault=count=0;
}
void getdata();
void page_fault();
};
void lru_alg::getdata()
{
cout<<"Enter Page reference string : ";
cin.getline(ref,50);
cout<<"Enter no. of frames : ";
cin>>frame;
}
void lru_alg::page_fault()
{
int flag=0;
for(int i=0;ref[i]!=0;i++)
{
if(ref[i]==' ')
continue;
if(front==NULL)
{
front=rear=new node;
front->data=ref[i];
front->next=NULL;
fault=count=1;
}
else
{
node *temp=front,*prev=NULL;
while(temp!=NULL)
{
if(temp->data==ref[i])
{
flag=1;
if(prev==NULL)
{
rear=rear->next=front;
front=front->next;
rear->next=NULL;
}
else if(temp!=rear)
{
prev->next=temp->next;
rear=rear->next=temp;
temp->next=NULL;
}
break;
}
prev=temp;
temp=temp->next;
}
if(flag==0)
{
if(count==frame)
{
rear=rear->next=front;
front=front->next;
rear->data=ref[i];
rear->next=NULL;
}
else
{
rear=rear->next=new node;
rear->data=ref[i];
rear->next=NULL;
count++;
}
fault++;
}
flag=0;
}
}
cout<<"Number of page faults : "<<fault;
}
int main()
{
lru_alg page;
page.getdata();
page.page_fault();
return 0;
}

You might also like