Write a program to implement LRU page replacement algorithm using C++

  The following c program will help you to implement LRU page replacement algorithm using C++

Enter number of frames: 3

Enter 20 pages: 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1

Number of Page Faults 12
Number of page hits 8

Table of Contents

C++ Program Code

   
 

/*;==========================================
; Title: Write a program to implement LRU page replacement algorithm.
; Owned: codenaive littleboy8506@  <[email protected]> <[email protected]>
; Contribution:  Mansi bansal
; Programming Language: C++
; Date:   9 Feb 2021
;==========================================*/
#include<iostream> 
using namespace std; 
 
int lru(int time[], int n){ int i, min = time[0], pos = 0; 
for(i = 1; i < n; ++i) 
{ 
if(time[i] < min) 
{ 
min  = time[i]; 
pos = i; 
} 
} 
return pos; 
} 
 
int main() 
{ 
int frameno, pageno=20, frames[10], page[30], count = 0, time[10], flag1, flag2, i, j, pos, pf = 0,hit=0; 
cout<<"Enter number of frames: "; cin>>frameno; cout<<"Enter 20 pages: "; for(i = 0; i < pageno; ++i) 
{ 
cin>>page[i]; 
} 
for(i = 0; i < frameno; ++i) 
{ 
frames[i] = -1; 
} 
for(i = 0; i < pageno; ++i) 
{ 
flag1 = flag2 = 0; 
for(j = 0; j < frameno; ++j) 
{ 
if(frames[j] == page[i]) 
{ 
count++; hit++; time[j] = count; flag1 = flag2 = 1; break; 
} 
} 
if(flag1 == 0) 
{ 
for(j = 0; j < frameno; ++j) 
{ 
if(frames[j] == -1) 
{ 
count++; pf++; frames[j] = page[i]; time[j] = count; flag2 = 1; 
break; 
} 
} 
} 
if(flag2 == 0) 
{ 
pos = lru(time, frameno); count++; pf++; frames[pos] = page[i]; 
time[pos] = count; 
} 
} 
cout<<"\n\nNumber of Page Faults    "<<pf; cout<<"\nNumber of page hits   "<<hit<<"\n";; 
return 0; 
} 
			 
						  		  
			 
						 					

Output

~/admin@codenaive/os $ g++ lru.cpp -o lru
~/admin@codenaive/os $ ./lru

Enter number of frames: 3
Enter 20 pages: 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1 

Number of Page Faults 12 
Number of page hits 8 



						

Leave a Reply

Your email address will not be published. Required fields are marked *