我正在实现一个简单的无序地图缓存,用
new
关键字,我希望在从缓存中移出对象时将其删除。作为参考,这是我正在使用的LRU缓存实现:
https://github.com/facebook/hhvm/blob/master/hphp/util/concurrent-lru-cache.h
我正在Linux上测试我的程序,1线程。代码如下:
HPHP::ConcurrentLRUCache<std::string, std::unordered_map<int, int>*> my_cache(10);
for (int i = 0; i < 1000000; i++) {
auto map = new std::unordered_map<int, int>(1000);
for (int j = 0; j < 1000; j++)
map->insert(std::make_pair(j, j));
my_cache.insert(std::to_string(i), map);
}
template <class TKey, class TValue, class THash>
bool ConcurrentLRUCache<TKey, TValue, THash>::
insert(const TKey& key, const TValue& value) {
// Insert into the CHM
ListNode* node = new ListNode(key);
HashMapAccessor hashAccessor;
HashMapValuePair hashMapValue(key, HashMapValue(value, node));
if (!m_map.insert(hashAccessor, hashMapValue)) {
delete node;
return false;
}
// Evict if necessary, now that we know the hashmap insertion was successful.
size_t size = m_size.load();
bool evictionDone = false;
if (size >= m_maxSize) {
evict();
evictionDone = true;
}
std::unique_lock<ListMutex> lock(m_listMutex);
pushFront(node);
lock.unlock();
if (!evictionDone) {
size = m_size++;
}
if (size > m_maxSize) {
if (m_size.compare_exchange_strong(size, size - 1)) {
evict();
}
}
return true;
}
template <class TKey, class TValue, class THash>
void ConcurrentLRUCache<TKey, TValue, THash>::
evict() {
std::unique_lock<ListMutex> lock(m_listMutex);
ListNode* moribund = m_tail.m_prev;
if (moribund == &m_head) {
// List is empty, can't evict
return;
}
delink(moribund);
lock.unlock();
HashMapAccessor hashAccessor;
if (!m_map.find(hashAccessor, moribund->m_key)) {
// Presumably unreachable
return;
}
m_map.erase(hashAccessor);
delete moribund;
}
插入映射时,如果缓存已满,则最近使用的元素应被逐出。但是,映射本身不会被删除,内存使用率也会达到峰值。我做错了什么?
注意:这些映射应该在我的程序执行期间被检索,因此它们应该可以从缓存中访问。