LRU算法的簡單實現( C語言 + uthash包)


什么是 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;
}
}
}




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM