From 655b46c495f5eda0c3eaa9dd9b8fa8fe1d87b1f4 Mon Sep 17 00:00:00 2001 From: Christian Krinitsin Date: Thu, 20 Mar 2025 14:06:44 +0100 Subject: server: add concurrency and edit gitignore --- src/server/hashtable.h | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) (limited to 'src/server') diff --git a/src/server/hashtable.h b/src/server/hashtable.h index 0989a79..786d8f5 100644 --- a/src/server/hashtable.h +++ b/src/server/hashtable.h @@ -3,7 +3,9 @@ #include #include #include +#include #include +#include #include template @@ -12,12 +14,16 @@ public: HashTable(size_t size) : size { size } , table(size) + , bucket_mutexes(size) { } bool insert(K key, V value) { - std::list>& list = get_bucket(key); + size_t index = get_bucket_index(key); + std::unique_lock lock(bucket_mutexes.at(index)); + + std::list>& list = table.at(index); if (bucket_contains_key(list, key)) { return false; @@ -30,7 +36,10 @@ public: std::optional get(K key) { - std::list>& list = get_bucket(key); + size_t index = get_bucket_index(key); + std::shared_lock lock(bucket_mutexes.at(index)); + + std::list>& list = table.at(index); auto iter = bucket_find_key(list, key); if (iter != list.end()) { @@ -42,7 +51,10 @@ public: bool remove(K key) { - std::list>& list = get_bucket(key); + size_t index = get_bucket_index(key); + std::unique_lock lock(bucket_mutexes.at(index)); + + std::list>& list = table.at(index); auto iter = bucket_find_key(list, key); if (iter != list.end()) { @@ -57,11 +69,13 @@ public: { size_t index { 0 }; for (auto bucket : table) { - std::cout << "Bucket " << index++ << ": ["; + std::cout << "Bucket " << index << ": ["; + std::shared_lock lock(bucket_mutexes.at(index)); for (auto pair : bucket) { std::cout << "(" << pair.first << ", " << pair.second << ")"; } std::cout << "]" << "\n"; + ++index; } } @@ -70,6 +84,8 @@ private: std::vector>> table; + std::vector bucket_mutexes; + std::hash hash_function; auto bucket_find_key(std::list>& list, K key) @@ -84,9 +100,5 @@ private: return list.begin() != list.end() && bucket_find_key(list, key) != list.end(); } - std::list>& get_bucket(K key) - { - size_t index = hash_function(key) % size; - return table.at(index); - } + size_t get_bucket_index(K key) { return hash_function(key) % size; } }; -- cgit 1.4.1