Add mutex to gets and puts

gets and puts both mutate the underling structures. Put in a mutex
and use a guard to make sure we're not stepping on ourselves.

This almost certainly could be smarter.
This commit is contained in:
Monty Taylor 2019-02-10 19:25:30 +00:00
parent c9245f61ec
commit 8dc7bfcf16
1 changed files with 6 additions and 1 deletions

View File

@ -47,15 +47,19 @@ class Cache {
// The maximum size of the cache.
const uint32_t size;
// Mutex protecting the map and list.
mutex cache_mutex;
public:
Cache(uint s)
: queue {}, map {}, size{s}
: queue {}, map {}, size{s}, cache_mutex{}
{ }
// Lookup the hostname in the cache and return the URL if present.
// If the entry is present, it is moved to the head of the queue.
optional<const string> get(const string &key)
{
lock_guard<mutex> guard{cache_mutex};
auto location = map.find(key);
if (location == map.end())
return {};
@ -71,6 +75,7 @@ public:
// recently used entry.
void put(const string &key, const string &value)
{
lock_guard<mutex> guard{cache_mutex};
auto location = map.find(key);
if (location != map.end())
return;