LRU算法实现思路

LRU

LRU算法一般是用在构建缓存上的,主要目的是在于怎么将部分缓存数据给淘汰掉。

开源组件

可以使用redis的链表与字典来实现一个demo,下面列出使用的redis结构体.

双向链表

typedef struct listNode {
    struct listNode *prev;
    struct listNode *next;
    void *value;
} listNode;

typedef struct list {
    listNode *head;
    listNode *tail;
    void *(*dup)(void *ptr);
    void (*free)(void *ptr);
    int (*match)(void *ptr, void *key);
    unsigned long len;
} list;

字典(Key-Val)


/* This is our hash table structure. Every dictionary has two of this as we
 * implement incremental rehashing, for the old to the new table. */
typedef struct dictht {
    dictEntry **table;
    unsigned long size;
    unsigned long sizemask;
    unsigned long used;
} dictht;

typedef struct dict {
    dictType *type;
    void *privdata;
    dictht ht[2];
    long rehashidx; /* rehashing not in progress if rehashidx == -1 */
    unsigned long iterators; /* number of iterators currently running */
} dict;

LRU需要的结构体

typedef struct SIMPLE_LRU_S
{
    pthread_rwlock_t stLock;        /* 锁,多线程使用 */
    dict stKV;                      /* 缓存KV,用于查找 */
    list stLi;                      /* 链表,用来淘汰,节点数据内存与stKV相同 */
    unsigned int ulMaxElemNum;      /* 最大元素个数 */
}SIMPLE_LRU_S;

对此,需要解释一下:

  • stLock是用在多线程上锁必须加的锁
  • stKV是用来缓存查找的,否则遍历速度较慢
  • stLi是为了淘汰链表尾部数据的
  • ulMaxElemNum是用来判定当前缓存最多使用的多少个数据,超过此数值,则淘汰

PlanUML流程图

在这里插入图片描述

@startuml SimpleLRU
title SimpeLRU

start

:调用缓存对外接口;
' 数据是否存在以及查找可以通过stKV去处理;
' 缓存中的数据个数通过stLi的len获取;
if (数据查找 ?) then(存在)
    :将数据从stLi当前位置移动到stLi的头部;
else (不存在)
    if (缓存中的数据个数是否 >= ulMaxElemNum ?) then(大于)
        :删除链表stLi尾部最后一个元素;
        :删除stKV中此数据的Key-Val映射;
    else (小于)
        :ignore;
    endif
    :调用业务API获取读取数据;
    :建立数据的Key-Val映射,放到stKV;
    :将数据的引用放到stLi的首部;
endif
:返回数据;
end

@enduml

参考资料


https://www.jianshu.com/p/d533d8a66795
https://www.iteye.com/blog/flychao88-1977653
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
LRU算法(最近最少使用算法)是一种用于缓存淘汰的算法。其原理是根据数据的访问时间来确定是否将其从缓存中删除。当缓存达到最大容量时,如果要插入新数据,则需要将最近最少使用的数据删除,以腾出空间。 以下是C++实现LRU算法的基本思路: 1. 使用一个双向链表来维护缓存的数据。 2. 使用一个哈希表来快速查找数据是否在缓存中。 3. 当一个数据被访问时,将其移动到链表头部。 4. 当需要插入新数据时,先检查缓存是否已满,如果已满,则删除链表尾部的数据,并将新数据插入到链表头部。 5. 当需要删除数据时,直接从链表中删除即可。 以下是C++代码示例: ``` #include <iostream> #include <unordered_map> using namespace std; class LRUCache { private: struct Node { int key; int value; Node* prev; Node* next; Node(int k, int v) : key(k), value(v), prev(nullptr), next(nullptr) {} }; int capacity; unordered_map<int, Node*> map; Node* head; Node* tail; void addToHead(Node* node) { node->prev = nullptr; node->next = head; if (head) { head->prev = node; } else { tail = node; } head = node; } void removeNode(Node* node) { if (node == head) { head = node->next; } else if (node == tail) { tail = node->prev; } else { node->prev->next = node->next; node->next->prev = node->prev; } } public: LRUCache(int cap) : capacity(cap), head(nullptr), tail(nullptr) {} int get(int key) { if (map.find(key) != map.end()) { Node* node = map[key]; removeNode(node); addToHead(node); return node->value; } else { return -1; } } void put(int key, int value) { if (map.find(key) != map.end()) { Node* node = map[key]; node->value = value; removeNode(node); addToHead(node); } else { Node* newNode = new Node(key, value); if (map.size() == capacity) { map.erase(tail->key); removeNode(tail); delete tail; } map[key] = newNode; addToHead(newNode); } } }; int main() { LRUCache cache(2); cache.put(1, 1); cache.put(2, 2); cout << cache.get(1) << endl; // 输出 1 cache.put(3, 3); // 删除 key 2 cout << cache.get(2) << endl; // 输出 -1 cache.put(4, 4); // 删除 key 1 cout << cache.get(1) << endl; // 输出 -1 cout << cache.get(3) << endl; // 输出 3 cout << cache.get(4) << endl; // 输出 4 return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值