Browse Source

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.
changes/91/636791/1
Monty Taylor 3 months ago
parent
commit
8dc7bfcf16
1 changed files with 6 additions and 1 deletions
  1. 6
    1
      zuul-preview/main.cc

+ 6
- 1
zuul-preview/main.cc View File

@@ -47,15 +47,19 @@ class Cache {
47 47
   // The maximum size of the cache.
48 48
   const uint32_t size;
49 49
 
50
+  // Mutex protecting the map and list.
51
+  mutex cache_mutex;
52
+
50 53
 public:
51 54
   Cache(uint s)
52
-    : queue {}, map {}, size{s}
55
+    : queue {}, map {}, size{s}, cache_mutex{}
53 56
   { }
54 57
 
55 58
   // Lookup the hostname in the cache and return the URL if present.
56 59
   // If the entry is present, it is moved to the head of the queue.
57 60
   optional<const string> get(const string &key)
58 61
   {
62
+    lock_guard<mutex> guard{cache_mutex};
59 63
     auto location = map.find(key);
60 64
     if (location == map.end())
61 65
       return {};
@@ -71,6 +75,7 @@ public:
71 75
   // recently used entry.
72 76
   void put(const string &key, const string &value)
73 77
   {
78
+    lock_guard<mutex> guard{cache_mutex};
74 79
     auto location = map.find(key);
75 80
     if (location != map.end())
76 81
       return;

Loading…
Cancel
Save