contributed by < Eric Lin >
Least recently used (LRU) is one of the Cache replacement policies. Caching improves performance by keeping recent or often-used data items in memory locations which are faster, or computationally cheaper to access, than normal memory stores. When the cache is full, the algorithm must choose which items to discard to make room for new data. And LRU discards least-recently-used items first.
source: wiki: Least_recently_used
Note: include/linux/types.h and include/linux/list.h have to be included.
Use circular doubly-linked list structure from include/linux/types.h:
LRUCache
capacity
: The maximum capacity of the cache.count
: The current number of data in the cache.dhead
: Recording the frequency of access for each node in the cache.hheads[]
: Implementing hash tables. Each index corresponds to a bucket in the hash table.LRUNode
key
: A unique key for hashing.value
: The data stored in the cache.hlink
: Link for chaining buckets having the same hash value in hash table.dlink
: Link for chaining nodes in the cache.Create LRUCache
and doing initialize.
Malloc capacity * sizeof(struct list_head)
is for hheads[]
.
The LRUCache maintains a list obj->dhead
, containing all the nodes currently present in the cache. Each node is connected by the lru->dlink link. Deleting these nodes effectively clears the cache.
key
.obj->hheads[hash]
and check for a matching key lru->key == key
.line 7
: If a matching key is found, the corresponding node is moved to the head of the obj->dhead
list, indicating that it is now the most recently used item.line 5
: If the key already exists, moves the corresponding node to the head of the list and updates its value.line 13
: If the cache is full. If the cache is full, replaces the least recently used node in the cache with the new data.