Sunday, March 23, 2014

LRU (Least Recently Used) Page Replacement (Memory Mangement) code : C++

#include "stdafx.h"
#include <iostream>
#define FFOR(i, j) for(int i=0;i<j;++i)
using namespace std;

/*Understandable, at least.*/

class LRU
{
public :
LRU()
{
FFOR(i, 10)
frames[i] = -1;
FFOR(i, 50)
pages[i]=0;

cout<<"Enter the number of pages: ";
cin>>nPages;

cout<<"Enter the number of frames: ";
cin>>nFrames;

cout<<"Enter the page numbers: ";
FFOR(i, nPages)
cin>>pages[i];

FFOR(i, nPages)
timeArr[i][0]=-1;
allocate();
}

void allocate()
{
int avail = 0;
int toReplace = 0;
static int time=0;
FFOR(i, nPages)
{
avail = 0;
time++;
timeArr[pages[i]][0] = time;

FFOR(j, nFrames)
{
if(frames[j] == pages[i])
{
avail = 1;
break;
}
}

if(avail==0)
{
if(frames[toReplace]==-1)
{
frames[toReplace] = pages[i];
toReplace = (toReplace+1) % nFrames;
}
else
{
//calculate toReplace
int min = INT_MAX;

FFOR(j, nFrames)
{
int pageNumber = frames[j];
if(timeArr[frames[j]][0]<min)
{
min=timeArr[frames[j]][0];
toReplace = j;
}
}
frames[toReplace] = pages[i];
}
}
}
display();
}

void display()
{
FFOR(i, nFrames)
{
cout<<frames[i]<<" ";
}
}

private:
int nFrames;
int timeArr[50][1];
int nPages;
int frames[10];
int pages[50];
};

int main()
{
LRU l;
}

No comments:

Post a Comment