操作系统课程设计之存储管理---最佳置换算法
源代码在线查看: optimal.txt
#include
#define Bsize 4
#define Psize 25
struct pageInfor
{
int content;//页面号
int timer;//被访问标记
};
class PRA
{
public:
PRA(void);
int findSpace(void);//查找是否有空闲内存
int findExist(int curpage);//查找内存中是否有该页面
int findReplace(void);//查找应予置换的页面
void display(void);//显示
void Optimal(void);//OPTIMAL算法
void BlockClear(void);//BLOCK恢复
pageInfor * block;//物理块
pageInfor * page;//页面号串
private:
};
PRA::PRA(void)
{
int QString[25]={7,0,1,2,0,3,0,5,2,3,0,3,2,1,2,0,1,7,0,1,4,5,6,7,0};
block = new pageInfor[Bsize];
for(int i=0; i {
block[i].content = -1;
block[i].timer = 0;
}
page = new pageInfor[Psize];
for(i=0; i {
page[i].content = QString[i];
page[i].timer = 0;
}
}
int PRA::findSpace(void)
{
for(int i=0; i if(block[i].content == -1)
return i;//找到空闲内存,返回BLOCK中位置
return -1;
}
int PRA::findExist(int curpage)
{
for(int i=0; i if(block[i].content == page[curpage].content)
return i;//找到内存中有该页面,返回BLOCK中位置
return -1;
}
int PRA::findReplace(void)
{
int pos = 0;
for(int i=0; i if(block[i].timer >= block[pos].timer)
pos = i;//找到应予置换页面,返回BLOCK中位置
return pos;
}
void PRA::display(void)
{
for(int i=0; i if(block[i].content != -1)
cout cout }
void PRA::Optimal(void)
{
int exist,space,position ;
for(int i=0; i {
exist = findExist(i);
if(exist != -1)
{ cout else
{
space = findSpace();
if(space != -1)
{
block[space] = page[i];
display();
}
else
{
for(int k=0; k for(int j=i; j {
if(block[k].content != page[j].content)
{ block[k].timer = 10000; }//将来不会用,设置TIMER为一个很大数
else
{
block[k].timer = j;
break;
}
}
position = findReplace();
block[position] = page[i];
display();
}
}
}
}
void PRA::BlockClear(void)
{
for(int i=0; i {
block[i].content = -1;
block[i].timer = 0;
}
}
void main(void)
{
cout
cout cout cout cout
cout int select;
PRA test;
while(select)
{
cin>>select;
switch(select)
{
case 0:
break;
case 1:
cout test.Optimal();
test.BlockClear();
cout break;
}
}
}