-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConcurrentHashMap.hpp
More file actions
60 lines (48 loc) · 1.38 KB
/
Copy pathConcurrentHashMap.hpp
File metadata and controls
60 lines (48 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#ifndef HASH_MAP_HPP
#define HASH_MAP_HPP
#include "HashBucket.hpp"
#include <vector>
#include <cstdint>
#include <functional>
#include <mutex>
constexpr size_t HASH_SIZE_DEFAULT = 2027; // prime number for better distribution
template <typename K, typename V, typename F = std::hash<K>>
class ConcurrentHashMap
{
private:
std::vector<HashBucket<K, V>> buckets;
F hashFn;
const size_t hashSize;
size_t computeHash(const K &key) const
{
return hashFn(key) % hashSize;
}
public:
ConcurrentHashMap(size_t hashSize_ = HASH_SIZE_DEFAULT) : buckets(hashSize_), hashSize(hashSize_) {}
~ConcurrentHashMap() = default;
ConcurrentHashMap(const ConcurrentHashMap &) = delete;
ConcurrentHashMap(ConcurrentHashMap &&) = delete;
ConcurrentHashMap &operator=(const ConcurrentHashMap &) = delete;
ConcurrentHashMap &operator=(ConcurrentHashMap &&) = delete;
bool find(const K &key, V &value) const
{
return buckets[computeHash(key)].find(key, value);
}
// If key already exists, update the value, else do nothing
void insert(const K &key, const V &value)
{
buckets[computeHash(key)].insert(key, value);
}
void erase(const K &key)
{
buckets[computeHash(key)].erase(key);
}
void clear()
{
for (auto &bucket : buckets)
{
bucket.clear();
}
}
};
#endif