-
Notifications
You must be signed in to change notification settings - Fork 0
/
concurrent_hashmap.h
49 lines (41 loc) · 1.14 KB
/
concurrent_hashmap.h
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
#ifndef WEB_SERVER_CONCURRENT_HASHMAP_H
#define WEB_SERVER_CONCURRENT_HASHMAP_H
#include <unordered_map>
#include <mutex>
#include <shared_mutex>
using std::unordered_map;
using std::shared_mutex, std::shared_lock, std::unique_lock;
template<class K, class V>
class concurrent_hashmap {
public:
int count(K key);
V get(K key);
void set(K key, V value);
void erase(K key);
private:
unordered_map<K, V> data;
mutable shared_mutex mutex;
};
template<class K, class V>
int concurrent_hashmap<K, V>::count(K key) {
shared_lock<shared_mutex> lock(this->mutex);
return this->data.count(key);
}
template<class K, class V>
V concurrent_hashmap<K, V>::get(K key) {
shared_lock<shared_mutex> lock(this->mutex);
return this->data[key];
}
template<class K, class V>
void concurrent_hashmap<K, V>::set(K key, V value) {
unique_lock<shared_mutex> lock(this->mutex);
this->data[key] = value;
}
template<class K, class V>
void concurrent_hashmap<K, V>::erase(K key) {
unique_lock<shared_mutex> lock(this->mutex);
if (this->data.count(key)) {
this->data.erase(key);
}
}
#endif //WEB_SERVER_CONCURRENT_HASHMAP_H