代码改变世界

LRU算法的简单实现( C语言 + uthash包)

2012-01-12 21:20  Haippy  阅读(5974)  评论(0编辑  收藏  举报

什么是 LRU?

LRU是Least Recently Used的缩写,即最近最少使用页面置换算法,是为虚拟页式存储管理服务的,LRU算法的提出,是基于这样一个事实:在前面几条指令中使用频繁的页面很可能在后面的几条指令中频繁使用。反过来说,已经很久没有使用的页面很可能在未来较长的一段时间内不会被用到,这就是著名的局部性原理 ——比内存速度还要快的cache,也是基于同样的原理运行的。因此,我们只需要在每次调换时,找到最近最少使用的那个页面调出内存。

什么是 uthash ?

uthash 是一个C语言的哈希表,支持各种结构类型的存储、添加、删除,这些操作都在固定的时间完成,跟哈希表本身的大小无关。键也可以是任何类型的数据。

uthash实现简单的 LRU cache

#include <string.h>
#include <uthash.h>
#define MAX_CACHE_SIZE 100000

struct CacheEntry {
char *key;
char *value;
UT_hash_handle hh;
};
struct CacheEntry *cache = NULL;

char *value find_in_cache(char *key)
{
struct CacheEntry *entry;
HASH_FIND_STR(cache, key, entry)
if (entry) {
// remove it (so the subsequent add will throw it on the front of the list)
HASH_DELETE(hh, cache, entry);
HASH_ADD_KEYPTR(hh, cache, entry->key, strlen(entry->key), entry);
return entry->value;
}
return NULL;
}

void add_to_cache(char *key, char *value)
{
struct CacheEntry *entry, *tmp_entry;
entry = malloc(sizeof(struct CacheEntry));
entry->key = strdup(key);
entry->value = strdup(value);
HASH_ADD_KEYPTR(hh, cache, entry->key, strlen(entry->key), entry);

// prune the cache to MAX_CACHE_SIZE
if (HASH_COUNT(cache) >= MAX_CACHE_SIZE) {
HASH_ITER(hh, cache, entry, tmp_entry) {
// prune the first entry (loop is based on insertion order so this deletes the oldest item)
HASH_DELETE(hh, cache, entry);
free(entry->key);
free(entry->value);
free(entry);
break;
}
}
}