请求分页管理页面置换算法----最近最少使用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;
}

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


猜你喜欢

转载自blog.csdn.net/weixin_39408986/article/details/80814621
今日推荐