C语言实现改进clock时钟算法
程序员文章站
2022-04-02 10:56:17
...
实验作业,欢迎大神指教
下图是测试数据及结果
clock_pro.c
/*
* clock_pro.c
*
* Created on: 2019年12月6日
* Author: zyli
*/
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define Maxblocks 3
int blocks[Maxblocks] = {};
int access[Maxblocks] = {};
int modify[Maxblocks] = {};
int pages_in_blocks = 0;
int is_modified = 0;
int aimed_i=-1;
bool is_aimed(int pn)
{
aimed_i=-1;
for(int i=0;i<pages_in_blocks;i++)
{
if(blocks[i]==pn)
{
aimed_i=i;
return true;
}
}
return false;
}
void loop()
{
int taotaip=0;
for(int j=0;j<2;j++)
{
for(int i=0;i<pages_in_blocks;i++)
{
if(!access[i]&&!modify[i])
{
taotaip=blocks[i];
for(;i<pages_in_blocks;i++)
{blocks[i]=blocks[i+1];access[i]=access[i+1];modify[i]=modify[i+1];}
if(!j) printf("第一圈有(0,0)的,是页面 %d,淘汰!把新进程放入队尾\n",taotaip);
else printf("第三圈有(0,0)的,是页面 %d,淘汰!把新进程放入队尾\n",taotaip);
return;
}
}
if(!j) printf("第一圈没有(0,0)的,接着找(0,1)的\n");
else printf("第三圈没有(0,0)的,即上一圈(第二圈)全为(0,1)\n");
for(int i=0;i<pages_in_blocks;i++)
{
if(!(!access[i]&&modify[i]))
{
access[i]=0;
}
else
{
taotaip=blocks[i];
for(;i<pages_in_blocks;i++)
{blocks[i]=blocks[i+1];access[i]=access[i+1];modify[i]=modify[i+1];}
if(!j) printf("第二圈有(0,1)的,是页面 %d,淘汰!第一个(0,1)之前的访问位全部置为0,并把新进程放入队尾\n",taotaip);
else printf("第四圈必有(0,1)的,将第一个(0,1)的,即页面%d淘汰!把新进程放入队尾\n",taotaip);
return;
}
}
printf("第二圈没有(0,1)的,但把所有访问位置为0了,接着第三圈找(0,0)的\n");
}
}
void clock_pro(int pn)
{
if(pages_in_blocks<Maxblocks)
{
if(is_aimed(pn))
{
access[aimed_i]=1;
printf("输入是否修改进程%d (0/1)\n",pn);
scanf("%d",&is_modified);
if(is_modified) modify[aimed_i]=1;
}
else
{
blocks[pages_in_blocks]=pn;
access[pages_in_blocks]=1;
modify[pages_in_blocks]=0;
pages_in_blocks++;
}
}
else
{
if(is_aimed(pn))
{
access[aimed_i]=1;
printf("输入是否修改进程%d (0/1)\n",pn);
scanf("%d",&is_modified);
if(is_modified) modify[aimed_i]=1;
}
else
{
loop();
blocks[Maxblocks-1]=pn;
access[Maxblocks-1]=1;
modify[Maxblocks-1]=0;
}
}
}
void print_blocks()
{
int cato=0;
printf("此时内存块里状态为:\n");
for(int i=0;i<pages_in_blocks;i++)
{
if(!access[i] && !modify[i]) cato=1;
if(!access[i] && modify[i]) cato=2;
if( access[i] && !modify[i]) cato=3;
if( access[i] && modify[i]) cato=4;
printf("%d %d %d ,对应第%d类型页面\n",blocks[i],access[i],modify[i],cato);
}
printf("\n");
}
int main()
{
for(int i=0;i<Maxblocks;i++){ blocks[i]=-1;access[i]=0;modify[i]=0;}
int n=0;
while(n>=0)
{
is_modified=0;
printf("输入此时进程对哪个页面访问,输入-1结束程序\n");
scanf("%d",&n);
if(n>=0)
{
clock_pro(n);
print_blocks();
}
}
system("pause");
return 0;
return 0;
}