-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathConcurrentMap.h
More file actions
114 lines (90 loc) · 3.07 KB
/
Copy pathConcurrentMap.h
File metadata and controls
114 lines (90 loc) · 3.07 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#ifndef CONCURRENT_MAP_H
#define CONCURRENT_MAP_H
#include "spinmutex.h"
#include "mutex"
#include "robin_hood.h"
namespace tns {
template<class TKey, class TValue>
class SimpleMap {
public:
inline void Insert(TKey &key, TValue value) {
this->container_[key] = value;
}
inline TValue Get(TKey &key) {
bool found;
return this->Get(key, found);
}
inline TValue Get(TKey &key, bool &found) {
auto it = this->container_.find(key);
found = it != this->container_.end();
if (found) {
return it->second;
}
return nullptr;
}
inline bool ContainsKey(TKey &key) {
auto it = this->container_.find(key);
return it != this->container_.end();
}
inline void Remove(TKey &key) {
this->container_.erase(key);
}
inline void ForEach(const std::function<bool(TKey &, TValue &)> &func) {
for (auto i: this->container_) {
if (func(i.first, i.second)) {
break;
}
}
}
SimpleMap() = default;
SimpleMap(const SimpleMap &) = delete;
SimpleMap &operator=(const SimpleMap &) = delete;
private:
robin_hood::unordered_map<TKey, TValue> container_;
};
template<class TKey, class TValue>
class ConcurrentMap {
public:
inline void Insert(TKey &key, TValue value) {
std::lock_guard<mz::spin_mutex> writerLock(this->containerMutex_);
this->container_[key] = value;
}
inline TValue Get(TKey &key) {
bool found;
return this->Get(key, found);
}
inline TValue Get(TKey &key, bool &found) {
std::lock_guard<mz::spin_mutex> writerLock(this->containerMutex_);
auto it = this->container_.find(key);
found = it != this->container_.end();
if (found) {
return it->second;
}
return nullptr;
}
inline bool ContainsKey(TKey &key) {
std::lock_guard<mz::spin_mutex> writerLock(this->containerMutex_);
auto it = this->container_.find(key);
return it != this->container_.end();
}
inline void Remove(TKey &key) {
std::lock_guard<mz::spin_mutex> writerLock(this->containerMutex_);
this->container_.erase(key);
}
inline void ForEach(const std::function<bool(TKey &, TValue &)> &func) {
std::lock_guard<mz::spin_mutex> writerLock(this->containerMutex_);
for (auto i: this->container_) {
if (func(i.first, i.second)) {
break;
}
}
}
ConcurrentMap() = default;
ConcurrentMap(const ConcurrentMap &) = delete;
ConcurrentMap &operator=(const ConcurrentMap &) = delete;
private:
mz::spin_mutex containerMutex_;
robin_hood::unordered_map<TKey, TValue> container_;
};
}
#endif