LRU Cache
【摘要】 /* * practice37_lru_cache.c — LRU Cache (PG buffer pool 淘汰策略简化版) * ================================================================ * 对应 PG 模块: * src/backend/storage/buffer/bufmgr.c — buffer...
/*
* practice37_lru_cache.c — LRU Cache (PG buffer pool 淘汰策略简化版)
* ================================================================
* 对应 PG 模块:
* src/backend/storage/buffer/bufmgr.c — buffer 管理
* src/backend/storage/buffer/freelist.c — free list (clock sweep, 不是 LRU)
* (注: PG 用 clock sweep 不是 LRU, 但 LRU 是经典淘汰策略, 很多 DB 用)
*
* 为什么重要:
* LRU (Least Recently Used) 是经典的缓存淘汰策略:
* - 缓存满了, 淘汰"最久没访问"的
* - 访问一个元素, 移到"最近使用"位置
* 核心数据结构: hash table + 双向链表
* - hash table: O(1) 查找 key
* - 双向链表: O(1) 移到头部/删除尾部
* 组合起来: O(1) 的 get/put/evict
*
* 核心结构:
* 每个节点同时在两个结构里:
* 1. hash table (链地址法): 按 key 快速查找
* 2. 双向链表 (dlist): 维护访问顺序 (头部=最近, 尾部=最久)
*
* 示意图:
* hash table: buckets[0] → [K1] → [K4] → NULL
* buckets[1] → [K2] → NULL
* buckets[2] → [K3] → [K5] → NULL
*
* dlist: head → [K3] ⇄ [K1] ⇄ [K5] ⇄ [K2] ⇄ [K4] ← tail
* (最近访问) (最久未访问)
*
* 访问 K2:
* 1. hash 查找: buckets[1] → 找到 K2
* 2. dlist 移到头部: head → [K2] ⇄ [K3] ⇄ [K1] ⇄ [K5] ⇄ [K4] ← tail
*
* 缓存满了插入 K6:
* 1. 淘汰尾部 K4 (最久未访问)
* 2. 从 hash 删除 K4
* 3. 从 dlist 删除 K4
* 4. 插入 K6: hash + dlist 头部
*
* 难度: ★★★☆☆ (组合数据结构, 练 hash + dlist)
*
* 学习目标:
* 1. hash table (链地址法, 解决冲突)
* 2. 双向链表 (复用 practice35)
* 3. 组合数据结构 (节点同时在两个结构里)
* 4. LRU 淘汰策略
*
* 编译: gcc -Wall -Wextra -O2 -o practice37 practice37_lru_cache.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
/* ============================================================
* 常量
* ============================================================ */
#define HASH_SIZE 16 /* hash 桶数 (2 的幂, 方便取模) */
#define CACHE_CAPACITY 4 /* 缓存容量 (最多存 4 个元素) */
/* ============================================================
* 数据结构
* ============================================================ */
/*
* LRU 节点
* 同时在 hash table 和 dlist 里:
* - hash_next: hash 链 (链地址法解决冲突)
* - prev/next: dlist 指针 (维护访问顺序)
*/
typedef struct LRUNode {
int key; /* 键 */
int value; /* 值 */
struct LRUNode *hash_next; /* hash 链: 下一个同桶节点 */
struct LRUNode *prev; /* dlist: 前驱 */
struct LRUNode *next; /* dlist: 后继 */
} LRUNode;
/*
* LRU 缓存
* hash table + dlist 组合
*/
typedef struct {
LRUNode *buckets[HASH_SIZE]; /* hash 桶数组 (链地址法) */
LRUNode *head; /* dlist 头 (最近访问) */
LRUNode *tail; /* dlist 尾 (最久未访问) */
int size; /* 当前元素数 */
int capacity; /* 最大容量 */
} LRUCache;
/* ============================================================
* 初始化工具 (已实现)
* ============================================================ */
/* 创建新节点 */
LRUNode *lru_node_create(int key, int value) {
LRUNode *node = (LRUNode *)malloc(sizeof(LRUNode));
assert(node != NULL);
node->key = key;
node->value = value;
node->hash_next = NULL;
node->prev = NULL;
node->next = NULL;
return node;
}
/* 释放节点 */
void lru_node_free(LRUNode *node) {
free(node);
}
/* 初始化缓存 */
void lru_cache_init(LRUCache *cache, int capacity) {
memset(cache->buckets, 0, sizeof(cache->buckets));
cache->head = NULL;
cache->tail = NULL;
cache->size = 0;
cache->capacity = capacity;
}
/* ============================================================
* TODO 1: 哈希函数 (简单版)
* 把 key 映射到 [0, HASH_SIZE) 的桶索引
*
* 简化版: key % HASH_SIZE (HASH_SIZE 是 2 的幂, 可以用位运算)
* 生产环境用更好的哈希 (避免冲突), 本题简化
*
* 提示: HASH_SIZE = 16 = 2^4, 所以 key % 16 = key & 15 = key & (16-1)
* ============================================================ */
int lru_cache_hash(int key) {
return key & (HASH_SIZE - 1);
}
/* ============================================================
* TODO 2: dlist 工具函数 (复用 practice35 的思路, 简化版)
* 头插、删除、移到头部
* ============================================================ */
/* 头插: 把 node 插到 dlist 头部 */
void dlist_push_front(LRUCache *cache, LRUNode *node) {
node->prev = NULL;
node->next = cache->head;
if(cache->head == NULL)
{
cache->tail = node;
} else {
cache->head->prev = node;
}
cache->head = node;
cache->size++;
}
/* 删除: 从 dlist 删除 node (不 free) */
void dlist_remove(LRUCache *cache, LRUNode *node) {
if(node->prev != NULL)
{
node->prev->next = node->next;
}else {
cache->head = node->next;
}
if(node->next !=NULL)
{
node->next->prev = node->prev;
}else {
cache->tail = node->prev;
}
cache->size--;
node->prev = node->next = NULL;
}
/* 移到头部: 把 node 移到 dlist 头部 */
void dlist_move_to_front(LRUCache *cache, LRUNode *node) {
if(cache->head == NULL)
{
return;
}
dlist_remove(cache, node);
dlist_push_front(cache, node);
}
/* ============================================================
* hash 工具函数 (已实现)
* ============================================================ */
/* hash 插入: 把 node 插到对应桶的头部 */
void hash_insert(LRUCache *cache, LRUNode *node) {
int bucket = lru_cache_hash(node->key);
node->hash_next = cache->buckets[bucket];
cache->buckets[bucket] = node;
}
/* hash 查找: 按 key 查找节点, 返回指针, 没找到返回 NULL */
LRUNode *hash_find(LRUCache *cache, int key) {
int bucket = lru_cache_hash(key);
for (LRUNode *p = cache->buckets[bucket]; p != NULL; p = p->hash_next) {
if (p->key == key) return p;
}
return NULL;
}
/* hash 删除: 从 hash 删除 node (不 free) */
void hash_remove(LRUCache *cache, LRUNode *node) {
int bucket = lru_cache_hash(node->key);
LRUNode **pp = &cache->buckets[bucket];
while (*pp != NULL) {
if (*pp == node) {
*pp = node->hash_next;
return;
}
pp = &(*pp)->hash_next;
}
}
/* ============================================================
* TODO 3: 查找 (get)
* 找到 key 对应的 value, 并移到头部 (标记为最近访问)
*
* 算法:
* 1. hash 查找 key
* 2. 找到 → 移到 dlist 头部, 返回 value
* 3. 没找到 → 返回 -1 (约定 -1 表示没找到, 假设 value 不会是 -1)
*
* 示例:
* cache: head → [K3=30] ⇄ [K1=10] ⇄ [K2=20] ← tail
* get(K1):
* 1. hash 查找 K1 → 找到 node (value=10)
* 2. 移到头部: head → [K1=10] ⇄ [K3=30] ⇄ [K2=20] ← tail
* 3. return 10
* ============================================================ */
int lru_cache_get(LRUCache *cache, int key) {
int bucket = lru_cache_hash(key);
for(LRUNode *p = cache->buckets[bucket]; p!=NULL; p = p->hash_next)
{
if(p->key == key)
{
dlist_move_to_front(cache,p);
return p->value;
}
}
return -1;
}
void lru_cache_evict(LRUCache *cache);
/* ============================================================
* TODO 4: 插入/更新 (put)
* 如果 key 已存在, 更新 value, 移到头部
* 如果 key 不存在, 插入新节点到头部
* 如果缓存满了, 先淘汰尾部 (最久未访问)
*
* 算法:
* 1. hash 查找 key
* 2. 找到 → 更新 value, 移到头部, return
* 3. 没找到:
* a. 如果 size == capacity, 淘汰尾部 (调用 lru_cache_evict)
* b. 创建新节点
* c. hash 插入
* d. dlist 头插
* e. size++
*
* 示例:
* cache (capacity=3): head → [K3=30] ⇄ [K1=10] ⇄ [K2=20] ← tail, size=3
* put(K4, 40):
* 1. hash 查找 K4 → 没找到
* 2. size==3 == capacity, 淘汰尾部 K2
* - 从 hash 删除 K2
* - 从 dlist 删除 K2
* - free(K2), size=2
* 3. 创建 K4=40
* 4. hash 插入 K4
* 5. dlist 头插: head → [K4=40] ⇄ [K3=30] ⇄ [K1=10] ← tail
* 6. size=3
* ============================================================ */
void lru_cache_put(LRUCache *cache, int key, int value){
LRUNode *node = hash_find(cache,key);
if(node != NULL)
{
node->value = value;
dlist_move_to_front(cache,node);
}else {
if(cache->size == cache->capacity)
{
lru_cache_evict(cache);
}
LRUNode *newNode = lru_node_create(key, value);
hash_insert(cache,newNode);
dlist_push_front(cache,newNode);
}
}
/* ============================================================
* TODO 5: 淘汰 (evict)
* 淘汰 dlist 尾部节点 (最久未访问)
*
* 算法:
* 1. 如果 tail == NULL (空缓存), return
* 2. 从 hash 删除 tail
* 3. 从 dlist 删除 tail
* 4. free(tail)
* 5. size--
*
* 示例:
* cache: head → [K3=30] ⇄ [K1=10] ⇄ [K2=20] ← tail
* evict():
* 1. tail = K2
* 2. hash 删除 K2
* 3. dlist 删除 K2: head → [K3=30] ⇄ [K1=10] ← tail
* 4. free(K2)
* 5. size=2
* ============================================================ */
void lru_cache_evict(LRUCache *cache) {
if(cache->tail ==NULL)
{
return;
}
LRUNode *node = cache->tail;
hash_remove(cache, node);
dlist_remove(cache, node);
lru_node_free(node);
}
/* ============================================================
* 工具函数 (已实现)
* ============================================================ */
void lru_cache_dump(const LRUCache *cache, const char *label) {
printf("--- %s (size=%d/%d) ---\n", label, cache->size, cache->capacity);
printf(" dlist (最近→最久): ");
for (LRUNode *p = cache->head; p != NULL; p = p->next) {
printf("[K%d=%d]", p->key, p->value);
if (p->next != NULL) printf(" ⇄ ");
}
printf("\n");
}
/* ============================================================
* 测试
* ============================================================ */
static void test_hash(void) {
printf("=== test_hash ===\n");
/* HASH_SIZE = 16 */
assert(lru_cache_hash(0) == 0);
assert(lru_cache_hash(1) == 1);
assert(lru_cache_hash(15) == 15);
assert(lru_cache_hash(16) == 0);
assert(lru_cache_hash(17) == 1);
assert(lru_cache_hash(31) == 15);
assert(lru_cache_hash(32) == 0);
printf(" 哈希函数: OK\n");
printf(" PASS\n\n");
}
static void test_basic_put_get(void) {
printf("=== test_basic_put_get ===\n");
LRUCache cache;
lru_cache_init(&cache, 3);
/* 插入 K1=10 */
lru_cache_put(&cache, 1, 10);
assert(cache.size == 1);
assert(lru_cache_get(&cache, 1) == 10);
lru_cache_dump(&cache, "插入 K1=10");
printf(" 插入 K1=10: OK\n");
/* 插入 K2=20 */
lru_cache_put(&cache, 2, 20);
assert(cache.size == 2);
assert(lru_cache_get(&cache, 2) == 20);
lru_cache_dump(&cache, "插入 K2=20");
printf(" 插入 K2=20: OK\n");
/* 插入 K3=30 */
lru_cache_put(&cache, 3, 30);
assert(cache.size == 3);
assert(lru_cache_get(&cache, 3) == 30);
lru_cache_dump(&cache, "插入 K3=30");
printf(" 插入 K3=30: OK\n");
/* 查找不存在的 key */
assert(lru_cache_get(&cache, 99) == -1);
printf(" 查找不存在的 K99 → -1: OK\n");
printf(" PASS\n\n");
}
static void test_update(void) {
printf("=== test_update ===\n");
LRUCache cache;
lru_cache_init(&cache, 3);
lru_cache_put(&cache, 1, 10);
lru_cache_put(&cache, 2, 20);
lru_cache_put(&cache, 3, 30);
lru_cache_dump(&cache, "初始: K1=10, K2=20, K3=30");
/* 更新 K2=200 */
lru_cache_put(&cache, 2, 200);
assert(cache.size == 3);
assert(lru_cache_get(&cache, 2) == 200);
/* K2 移到头部 */
assert(cache.head->key == 2);
assert(cache.head->value == 200);
lru_cache_dump(&cache, "更新 K2=200 (移到头部)");
printf(" 更新 K2=200, 移到头部: OK\n");
printf(" PASS\n\n");
}
static void test_lru_eviction(void) {
printf("=== test_lru_eviction ===\n");
LRUCache cache;
lru_cache_init(&cache, 3);
/* 插入 K1, K2, K3 */
lru_cache_put(&cache, 1, 10);
lru_cache_put(&cache, 2, 20);
lru_cache_put(&cache, 3, 30);
lru_cache_dump(&cache, "初始: K1, K2, K3 (size=3)");
assert(cache.size == 3);
/* 访问 K1 (移到头部) */
lru_cache_get(&cache, 1);
lru_cache_dump(&cache, "访问 K1 (移到头部)");
assert(cache.head->key == 1);
/* 插入 K4 (满了, 淘汰尾部 K2) */
lru_cache_put(&cache, 4, 40);
assert(cache.size == 3);
assert(lru_cache_get(&cache, 2) == -1); /* K2 被淘汰 */
assert(lru_cache_get(&cache, 1) == 10); /* K1 还在 */
assert(lru_cache_get(&cache, 3) == 30); /* K3 还在 */
assert(lru_cache_get(&cache, 4) == 40); /* K4 刚插入 */
lru_cache_dump(&cache, "插入 K4 (淘汰 K2)");
printf(" 满了淘汰最久未访问 K2: OK\n");
printf(" PASS\n\n");
}
static void test_evict_function(void) {
printf("=== test_evict_function ===\n");
LRUCache cache;
lru_cache_init(&cache, 3);
lru_cache_put(&cache, 1, 10);
lru_cache_put(&cache, 2, 20);
lru_cache_put(&cache, 3, 30);
lru_cache_dump(&cache, "初始: K1, K2, K3");
/* 手动淘汰尾部 */
lru_cache_evict(&cache);
assert(cache.size == 2);
assert(lru_cache_get(&cache, 1) == -1); /* K1 是尾部, 被淘汰 */
lru_cache_dump(&cache, "淘汰尾部 K1");
printf(" 手动淘汰尾部 K1: OK\n");
/* 再淘汰一次 */
lru_cache_evict(&cache);
assert(cache.size == 1);
assert(lru_cache_get(&cache, 2) == -1); /* K2 是尾部, 被淘汰 */
lru_cache_dump(&cache, "再淘汰 K2");
printf(" 再淘汰 K2: OK\n");
/* 再淘汰一次, 把最后一个 K3 也淘汰 */
lru_cache_evict(&cache);
assert(cache.size == 0);
assert(lru_cache_get(&cache, 3) == -1); /* K3 被淘汰 */
lru_cache_dump(&cache, "淘汰最后一个 K3");
printf(" 淘汰最后一个 K3: OK\n");
/* 空缓存淘汰 (应该无操作) */
lru_cache_evict(&cache);
assert(cache.size == 0); /* 不变 */
printf(" 空缓存淘汰 (无操作): OK\n");
printf(" PASS\n\n");
}
static void test_complex_scenario(void) {
printf("=== test_complex_scenario ===\n");
LRUCache cache;
lru_cache_init(&cache, 3);
/* 模拟真实场景 */
lru_cache_put(&cache, 1, 10); /* [K1] */
lru_cache_put(&cache, 2, 20); /* [K2, K1] */
lru_cache_put(&cache, 3, 30); /* [K3, K2, K1] */
lru_cache_get(&cache, 1); /* [K1, K3, K2] 访问 K1, 移到头部 */
lru_cache_put(&cache, 4, 40); /* [K4, K1, K3] 淘汰 K2 (尾部) */
lru_cache_get(&cache, 3); /* [K3, K4, K1] 访问 K3, 移到头部 */
lru_cache_put(&cache, 5, 50); /* [K5, K3, K4] 淘汰 K1 (尾部) */
lru_cache_dump(&cache, "复杂场景后");
assert(cache.size == 3);
assert(lru_cache_get(&cache, 1) == -1); /* K1 被淘汰 */
assert(lru_cache_get(&cache, 2) == -1); /* K2 被淘汰 */
assert(lru_cache_get(&cache, 3) == 30); /* K3 还在 */
assert(lru_cache_get(&cache, 4) == 40); /* K4 还在 */
assert(lru_cache_get(&cache, 5) == 50); /* K5 还在 */
printf(" 复杂场景: OK\n");
printf(" PASS\n\n");
}
int main(void) {
test_hash();
test_basic_put_get();
test_update();
test_lru_eviction();
test_evict_function();
test_complex_scenario();
printf("========================================\n");
printf("practice37 全部通过!\n");
printf("========================================\n");
return 0;
}
/*
* 进阶思考题:
*
* 1. 为什么 LRU 要 hash + dlist 组合? 只用其中一个行不行?
* (提示: 只用 hash: O(1) 查找, 但不知道哪个最久没访问, 淘汰要 O(n) 扫描
* 只用 dlist: O(1) 淘汰尾部, 但查找要 O(n) 遍历
* 组合: hash O(1) 查找 + dlist O(1) 淘汰 = 整体 O(1))
*
* 2. 为什么 PG 不用 LRU 而用 clock sweep?
* (提示: LRU 需要维护 dlist, 每次访问都要移到头部, 锁竞争大
* clock sweep: 环形数组 + 指针, 不用移动, 锁竞争小
* LRU 适合小缓存, clock sweep 适合大缓存如 PG shared_buffers)
*
* 3. hash 冲突怎么解决? 本题用什么方法?
* (提示: 链地址法 (chaining): 同桶节点用链表串起来
* 还有开放地址法 (linear probing, quadratic probing)
* 本题用链地址法, 简单直观)
*
* 4. 为什么 HASH_SIZE 是 2 的幂?
* (提示: 2 的幂可以用位运算取模: key % 16 = key & 15 = key & (16-1)
* 位运算比除法快)
*
* 5. 如果 hash 函数很差 (比如所有 key 都映射到同一个桶), 会怎样?
* (提示: 退化成链表查找, O(n)
* 好的 hash 函数应该均匀分布, 减少冲突)
*
* 6. LRU 的变种有哪些?
* (提示: LFU (Least Frequently Used): 按访问频率淘汰
* ARC (Adaptive Replacement Cache): 自适应 LRU + LFU
* 2Q/T2Q: 双队列, 新插入先放 Q0, 访问多次再放 Q1 (LRU))
*
* 7. 为什么 get 要把节点移到头部?
* (提示: 标记为"最近访问", 避免被淘汰
* LRU 的精髓: 最近访问的保留, 最久没访问的淘汰)
*
* 8. 如果缓存容量是 100 万, hash 桶数设多少合适?
* (提示: 通常设容量的 1.5-2 倍, 减少冲突
* 本题 capacity=4, hash_size=16, 比例 4:1, 偏大
* 生产环境: capacity=1M, hash_size=2M 左右)
*/
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)