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