20 #include <unordered_map> 28 template<
typename Key,
typename Value>
33 std::shared_ptr<Value>
query(
const Key& key)
const;
42 template<
typename Func>
43 std::shared_ptr<Value>
test_insert(
const Key& key, Func craft);
46 void _house_keeping();
48 mutable std::mutex _mutex;
49 int _count_to_house_keeping = 2;
50 std::unordered_map<Key, std::weak_ptr<Value>> _map;
53 template<
typename Key,
typename Value>
56 _count_to_house_keeping = 0;
57 for (
auto it = _map.begin(); it != _map.end();)
59 if (it->second.expired())
63 ++_count_to_house_keeping;
69 template<
typename Key,
typename Value>
72 std::lock_guard<std::mutex> lock(_mutex);
73 auto ite = _map.find(key);
74 if (ite != _map.end())
76 std::shared_ptr<Value> v = ite->second.lock();
83 template<
typename Key,
typename Value>
84 template<
typename Func>
87 std::lock_guard<std::mutex> lock(_mutex);
90 auto result = _map.emplace(key, std::shared_ptr<Value>());
91 std::shared_ptr<Value> v = result.first->second.lock();
95 result.first->second = v;
97 --_count_to_house_keeping;
98 if (_count_to_house_keeping <= 0)
std::shared_ptr< Value > query(const Key &key) const
Query the cache with a key, returns nullptr if no entry is available.
Definition: Cache.h:70
std::shared_ptr< Value > test_insert(const Key &key, Func craft)
Test and insert a cache value.
Definition: Cache.h:85