您的位置:首页 > 其它

简单Clock算法

2015-06-16 16:05 507 查看

算法过程:

简单Clock算法需要根据页面内存是否被访问来决定是否置换该页面。实际编程中,与最近最久未置换算法类似,用整型数组来表示当前每个内存页面是否被访问,其中1代表被访问过,0代表未访问过。每次置换,指针循环遍历,找出第一个访问位不为1的那个内存页面。并且在找到被置换页面之前,将所经过的所有页面内存对应的访问位置0.

在内存块初始化后,取出页面访问序列队列的队头。首先判断内存块中是否已经存在该队头页面,如果存在则直接显示内存块当前情况,相应访问位置1,指针循环下移;若不存在,循环遍历内存块,找出第一个访问位不为1的那个内存页面。并且在找到被置换页面之前,将所经过的所有页面内存对应的访问位置置0. 如果找到的内存页面不为空闲位,则将缺页数加1. 如此循环迭代,直到页面访问序列队列为空时,整个算法执行完毕。最后计算并显示缺页率。其流程图如图所示:



代码示例:
#ifndef PAGEREPLACEMENT_H
#define PAGEREPLACEMENT_H

#include <vector>

class PageReplacement
{
public:
	PageReplacement();
	~PageReplacement();
	void run();
	void clock();

private:
	void addInfo() const;

private:
	int pages;					// 虚拟内存的尺寸P
	int firstPageFramePos;		// 工作面的起始位置p
	int pageFrames;				// 工作面中包含的页数e
	int rateM;					// 工作面移动率m
	std::vector<int> seqVec;	// 序列号
	std::vector<int> mem;		// 内存块
};

#endif	// PAGEREPLACEMENT_H
#include "PageReplacement.h"
#include <iostream>
#include <cstdlib>
#include <list>

PageReplacement::PageReplacement()
	: mem(3, -1)
{
	this->run();
}

PageReplacement::~PageReplacement()
{
}

void PageReplacement::run()
{
	std::cout << "请输入虚拟内存尺寸P:";
	std::cin >> pages;
	std::cout << "请输入工作面的起始位置p:";
	std::cin >> firstPageFramePos;
	std::cout << "请输入工作面中包含的页数e:";
	std::cin >> pageFrames;
	std::cout << "请输入工作面移动率m:";
	std::cin >> rateM;
	std::cout << "请输入在0和1之间的值t:";
	std::cin >> t;

	for (int i = 0; i < rateM; ++i)
	{
		int randomNum = (rand() % pageFrames) + firstPageFramePos;
		seqVec.push_back(randomNum);
	}

	std::cout << "序列号:";
	for (int i = 0; i < seqVec.size(); ++i)
	{
		std::cout << seqVec.at(i) << " ";
	}

	std::cout << std::endl;
}

void PageReplacement::clock()
{
	int nLack = 0;			// 缺页数
	std::list<int> seqList(seqVec.begin(), seqVec.end());
	int nTotal = seqList.size();

	std::vector<int> timer(mem.size(), 0);
	int cursor = 0;			// 当前的时钟指针

	while (!seqList.empty())
	{
		int head = *seqList.begin();		// 去掉队头的页面
		seqList.pop_front();

		int p = 0;

		// 遍历内存块,找到与队头页面相等的内存块
		for(p ; p < mem.size(); ++p)
		{
			if (mem.at(p) == head)		// 如果找到,将其时钟访问位置1,时钟指针往下移
			{
				timer[p] = 1;
				cursor = p;
				cursor = (cursor + 1) % timer.size();

				this->addInfo();
				break;
			}
		}

		if (p == mem.size())	// 如果没有找到
		{
			// 循环移动clock指针,知道找到访问位不为1的第一个内存块
			while (timer[cursor] == 1)
			{
				timer[cursor] = 0;
				cursor = (cursor + 1) % timer.size();
			}

			++nLack;

			mem[cursor] = head;
			timer[cursor] = 1;
			cursor = (cursor + 1) % timer.size();
			this->addInfo();
		}
	}

	std::cout << "缺页率: " << (double)nLack/nTotal * 100 << "%" << std::endl;
}

void PageReplacement::addInfo() const
{ 
	std::cout << mem.at(0) << "    " <<  mem.at(1) << "    "  << mem.at(2) << std::endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: