diff --git a/src/LRUCache.h b/src/LRUCache.h index f101b3b..36f8064 100644 --- a/src/LRUCache.h +++ b/src/LRUCache.h @@ -6,13 +6,16 @@ #include #include #include +#include +#include template class LRUCache { - using Key_list = std::list>; + using Key_list = std::list>>; Key_list key_values; std::unordered_map positions; size_t max_values; + std::mutex cache_mutex; void remove_oldest() { while (positions.size() >= max_values) { @@ -25,17 +28,30 @@ public: LRUCache(const size_t max_values) : max_values(max_values) { } - template - void insert(const K& key, VV&& value) { + void insert(const K& key, std::shared_ptr value) { + std::lock_guard lock(cache_mutex); remove_oldest(); key_values.emplace_front(key, value); positions[key] = key_values.begin(); } - std::pair find(const K& key) { + void insert(const K& key, V* value) { + insert(key, std::shared_ptr(value)); + } + + void insert(const K& key, V&& value) { + insert(key, std::make_shared(std::move(value))); + } + + void insert(const K& key, V& value) { + insert(key, std::make_shared(value)); + } + + std::shared_ptr find(const K& key) { + std::lock_guard lock(cache_mutex); auto p = positions.find(key); if (p == positions.end()) - return {nullptr, false}; + return {}; auto iter = p->second; auto& value = iter->second; // If the iterator is not at the front of the list, move it there. @@ -47,12 +63,13 @@ public: std::next(iter)); } positions[key] = key_values.begin(); - return {&(iter->second), true}; + return iter->second; } void debug_cache() { + std::lock_guard lock(cache_mutex); for (auto& p : key_values) { - std::cout << p.first << ":" << p.second << std::endl; + std::cout << p.first << ":" << *p.second << std::endl; } } }; diff --git a/tests/LRUCache-test.cpp b/tests/LRUCache-test.cpp index d6cc95a..beed296 100644 --- a/tests/LRUCache-test.cpp +++ b/tests/LRUCache-test.cpp @@ -7,7 +7,7 @@ using namespace std; int main(int argc, char **argv) { LRUCache lru(4); - lru.insert("hello", 1); + lru.insert("hello", new int(1)); lru.insert("hi", 2); lru.insert("where", 3); lru.insert("are", 4);