LRU
#include <stdio.h> #include <stdlib.h> #define mSIZE 3//分配三个内存页块 #define pSIZE 12//总共12个进程 struct mem { int num; int count; }memery[3]={0,-1,0,-1,0,-1}; static int process[pSIZE] ={1,2,3,4,1,2,5,1,2,3,4,5};//页面访问序列 void LRU(); void get(); int main() { get(); printf("\n(LRU)\treplace\n"); LRU(); system("PAUSE"); return 0; } void get() { int w[12]={1,2,3,4,1,2,5,1,2,3,4,5}; int i,n; for(i=0;i<12;i++) { printf("%d ",w[i]); } } void LRU() { int i = 0, j = 0,k=0,x,y; int replace; for(i = 0; i<pSIZE; i++) //对输入序列进行循环 { x=0;y=0; //置x,y初值为0 for(j = 0; j < mSIZE; j++) //对三个内存块进行循环,先查找有没有与即将访问页号相同的 if(memery[j].num == process[i]) { x=1;//有相同的则置x为1 replace=process[i]; memery[j].count=0;//置此块count为0 for(k=0;k<3;k++) if(k!=j&&memery[k].num!=0)memery[k].count++;//其他不为0页count++ break;//跳出此次内存块循环 } if(x==0)//没有与即将访问页号相同的内存块 { for(j = 0; j < mSIZE; j++)//对内存块循环,查找有没有空内存块 if(memery[j].num== 0) { y=1;//有则置y为1 replace=0; memery[j].num=process[i];// 置此内存块为访问页号 memery[j].count=0;//置此块count为0 for(k=0;k<3;k++) if(k!=j&&memery[k].num!=0)memery[k].count++;//其他不为0页count++ break;//跳出此次内存块循环 } } if(x==0&&y==0)//既没有与即将访问页号相同的内存块也没有空内存块 { int m=memery[0].count; for(j = 0; j < mSIZE; j++) { if(memery[j].count>m) m=memery[j].count; }//查找出count最大的内存块m for(j=0;j<mSIZE;j++)//对内存块循环,count=m的内存块 { if(memery[j].count==m) { replace=memery[j].num; memery[j].num=process[i]; //置此内存块为访问页号块 memery[j].count=0;//置此块count为0 } else memery[j].count++;//其他块count++ } } for(j = 0 ;j < mSIZE; j++) //打印每次访问后的情况 printf("%d ",memery[j].num); printf("\t%d\n",replace); } }