Sunday, April 6, 2014

LRU (Least Recently Used) Page Replacement: Memory Management (Clock Method) : C++

#include "stdafx.h"
#include <iostream>

using namespace std;

void main()
{
cout<<"Enter the number of page frames: ";
int nFrames = 0;
cin>>nFrames;

int frame[10][2];
for(int i =0;i<nFrames;++i)
{
frame[i][0]=-1; //page address set to -1
frame[i][1]=-1; //clock set to -1
}

cout<<"Enter the number of elements in page address stream: ";
int nStream=0;
cin>>nStream;

cout<<"Input the page address stream: ";
int stream[50];

for(int i = 0;i<nStream; ++i)
{
cin>>stream[i];
}

cout<<endl;
cout<<"Page address stream\t\tPage Frames\n";
cout<<"        ";
for(int i =0;i<nFrames;++i)
{
cout<<i<<"\t";
}
cout<<endl<<endl;

//ALLOCATION TO BE DONE HERE
int time=0;
int point = 0;

for(int i =0;i<nStream;++i)
{
if(frame[point][0]==-1)
{
for(int j=0;j<nFrames;++j)
  {
   if(frame[j][0]==stream[i])
   {
  frame[j][1]=time;

cout<<stream[i]<<"           \t\t\t";
    for(int k=0;k<nFrames;++k)
    {
     cout<<frame[k][0]<<"\t";
    }
    cout<<endl;  
 
break;
   }
   else if(frame[j][0]!=stream[i])
   {
    frame[point][0]=stream[i];
frame[point][1] = time;
    cout<<stream[i]<<"           \t\t\t";

for(int k=0;k<nFrames;++k)
    {
     cout<<frame[k][0]<<"\t";
    }
    cout<<endl;
   
point = (point+1)%nFrames;
    break;
   }
  }
 }
 else
 {
 int flag = 1;
 for(int j = 0;j<nFrames;++j)
 {
 if(frame[j][0]==stream[i])
 {
 frame[j][1]=time;

 cout<<stream[i]<<"           \t\t\t";
 for(int k=0;k<nFrames;++k)
 {
 cout<<frame[k][0]<<"\t";
 }
 cout<<endl;

 flag = 0;
 break;
 }
 }
 if(flag)
 {
 int min = INT_MAX;
 int minIndex=-1;
 for(int j=0;j<nFrames;++j)
 {
 if(frame[j][1]<min)
 {
 min = frame[j][1];
 minIndex= j;
 }
 }
 frame[minIndex][0] = stream[i];
 frame[minIndex][1] = time;

 cout<<stream[i]<<"           \t\t\t";
 for(int k=0;k<nFrames;++k)
 {
     cout<<frame[k][0]<<"\t";
 }
 cout<<endl;
 }
 }
time++;
}
}

No comments:

Post a Comment