-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_safe_map.hpp
More file actions
65 lines (54 loc) · 1.24 KB
/
thread_safe_map.hpp
File metadata and controls
65 lines (54 loc) · 1.24 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
#pragma once
#include<map>
#include<mutex>
#include<shared_mutex>
#include<iostream>
#include<vector>
using std::map;
using std::shared_mutex;
using std::shared_lock;
using std::unique_lock;
using std::cout;
using std::endl;
using std::vector;
template<typename T1, typename T2>
class thread_safe_map {
public:
thread_safe_map() = default;
thread_safe_map(thread_safe_map& map) = delete;
thread_safe_map(thread_safe_map&& moveable_map) {
unique_lock<shared_mutex> ul(map_mutex);
safe_map = move(moveable_map.safe_map);
}
T2 operator[](T1 key) {
shared_lock<shared_mutex> sl(map_mutex);
return safe_map[key];
}
bool contains(T1 key) {
shared_lock<shared_mutex> sl(map_mutex);
bool in_map = false;
if (safe_map.find(key) != safe_map.end()) {
in_map = true;
}
return in_map;
}
void write(T1 key, T2 value) {
unique_lock<shared_mutex> ul(map_mutex);
safe_map[key] = value;
}
vector<T1> get_keys() {
shared_lock<shared_mutex> sl(map_mutex);
vector<T1> keys;
for (auto i = safe_map.begin(); i != safe_map.end(); ++i) {
keys.push_back((*i).first);
}
return keys;
}
void erase(T1 key) {
unique_lock<shared_mutex> ul(map_mutex);
safe_map.erase(key);
}
private:
map<T1, T2> safe_map;
shared_mutex map_mutex;
};