LRU页面置换

#pragma once

#include "double_queue.h"


#include 


#define MAX_BLOCK 3

class LruCache {

public:
	LruCache(int block = MAX_BLOCK) {
		this->max_block = block;
		mem_queue = create_double_queue();
	}

	~LruCache() {
		this->max_block = 0;
		flag_map.clear();
		// destroy(mem_queue); 
	}

	bool push(const mem_block& block) {
		double_queue_node* node = NULL;
		if (size() < max_size()) {// 没有满
			auto iter = flag_map.find(block.key);
			if (iter == flag_map.end()) { // 没有找到
				node = create_double_queue_node((void*)&block);
				push_double_queue(mem_queue, node); // 尾插
				flag_map[block.key] = node;
			}
			else {
				(*iter).second = delete_node_node(mem_queue, (*iter).second);
				push_double_queue(mem_queue, (*iter).second); // 尾插
			}
		}
		else {// 满了
			auto iter = flag_map.find(block.key);
			if (iter != flag_map.end()) { // 找到了
				(*iter).second = delete_node_node(mem_queue, (*iter).second);
				push_double_queue(mem_queue, (*iter).second); // 尾插
			}
			else {
				auto del_node = top(mem_queue);
				flag_map.erase(((mem_block*)del_node->val)->key);
				pop_double_queue(mem_queue); // 删除最后最久没有用的

				node = create_double_queue_node((void*)&block);
				push_double_queue(mem_queue, node); // 尾插
				flag_map[block.key] = node;
			}
		}

		return true;
	}

	bool pop() {
		return false;
	}

	int size() {
		return double_queue_size(mem_queue);
	}

	int max_size() {
		return this->max_block;
	}

	double_queue* get_mem_queue() { return mem_queue; }
private:
	double_queue* mem_queue;
	std::unordered_map flag_map; // key, 位置
	int max_block;  // 最大内存块数量 
};

你可能感兴趣的:(算法,算法)