请求分页管理页面置换算法----最近最少使用LRU

该算法的性能接近于最佳算法,但实现起来较困难。因为要找出最近最少使用的页面,必须为每一页设置相关记录项,用于记录页面的访问情况,并且每访问一次页面都须更新该信息。这将使系统的开销加大,所以在实际系统中往往使用该算法的近似算法。这里会给出LRU算法的C++源码:

// LRU.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
#include "windows.h"
using namespace std;

//signal&constant values
#define N 3
//#define P 5
//int lack=0;//the signal showing numbers of pages of lackness,0 stands for nothing
int physicalBlock[N];//empty or full block

struct stack{//queue struct
	int pageNumber[N];
	int top;
	int pop;
}stack1;

void initializeBlocks(){//initialize all variables
	for(int i=0;i<N;i++){
		physicalBlock[i]=0;
		stack1.pageNumber[i]=0;
		stack1.top=0;
		stack1.pop=0;
	}
}

int main(int argc, char* argv[])
{
	int sq[12];
	int s=0;
	int lack=0;//record the number of lacked pages
	float lackpagesRate;//=lack/12
	initializeBlocks();
	printf("please input the sequence of pages:\n");
	for(int i=0;i<12;i++){//initialize the sequence of pages
		cin>>sq[i];
		//cout<<sq[i];
	}
	for(int j=0;j<12;j++){
		if(stack1.pageNumber[0]==sq[j]){//if the queue has the number of the page,don't change anything except pop pointer
			printf("This page exist!You don't have to replace it!\n");
			stack1.pop++;
			continue;
		}
		else if(stack1.pageNumber[1]==sq[j]){
			printf("This page exist!You don't have to replace it!\n");
			stack1.pop++;
			continue;	
		}
		else if(stack1.pageNumber[2]==sq[j]){
			printf("This page exist!You don't have to replace it!\n");
			stack1.pop++;
			continue;
		}
		else{ 
			if(physicalBlock[(s)%3]==0){
					lack++;
					stack1.pageNumber[stack1.top++]=sq[j];
					cout<<"page"<<sq[j]<<"is allocated to physicalBlock "<<stack1.top<<endl;
					physicalBlock[(s)%3]=1;
					s++;
			}
			else{
				lack++;
				stack1.pageNumber[(stack1.pop)%3]=sq[j];
				if((stack1.pop+1)%3!=0){
					cout<<"The page of physicalBlock "<<(stack1.pop+1)%3<<" is changed to "<<sq[j]<<endl;}
				else {cout<<"The page of physicalBlock 3 is changed to "<<sq[j]<<endl;}
				stack1.pop++;
			}
				
		}
	}
	cout<<"The number of lacked pages is:"<<lack<<endl;
	lackpagesRate=(float)lack/12;
	cout<<"The rate of lacked pages is:"<<lackpagesRate<<endl;
	//printf("Hello World!\n");
	system("pause");
	return 0;
}

通过队列实现最久页面替换。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值