#ifndef _ZD_LRU_CACHE_H_
#define _ZD_LRU_CACHE_H_
#include
#include
#include
class ZDLRUCahce
{
public:
ZDLRUCahce(int capacity)
: m_capacity(capacity)
{
}
~ZDLRUCahce()
{
}
int Get(int key)
{
RecursiveGuard mtx(m_recursive_mutex);
auto it = m_mapCache.find(key);
if (it == m_mapCache.end())
return -1;
std::pair<int, int> kv = *m_mapCache[key];
m_listCache.erase(m_mapCache[key]);
m_listCache.push_front(kv);
m_mapCache[key] = m_listCache.begin();
return kv.second;
}
void Put(int key, int value)
{
RecursiveGuard mtx(m_recursive_mutex);
auto it = m_mapCache.find(key);
if (it != m_mapCache.end())
{
m_listCache.erase(m_mapCache[key]);
m_listCache.push_front(std::make_pair(key, value));
m_mapCache[key] = m_listCache.begin();
return;
}
if (m_listCache.size() == m_capacity)
{
auto iter = m_listCache.back();
m_mapCache.erase(iter.first);
m_listCache.pop_back();
m_listCache.push_front(std::make_pair(key, value));
m_mapCache[key] = m_listCache.begin();
}
else
{
m_listCache.push_front(std::make_pair(key, value));
m_mapCache[key] = m_listCache.begin();
}
}
private:
int m_capacity;
typedef std::lock_guard<std::recursive_mutex> RecursiveGuard;
typedef std::list<std::pair<int, int>> Cache;
typedef std::unordered_map<int, Cache::iterator> CacheMap;
std::recursive_mutex m_recursive_mutex;
Cache m_listCache;
CacheMap m_mapCache;
};
#endif
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79