-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconcurrent_map.h
65 lines (50 loc) · 1.37 KB
/
concurrent_map.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <cstdlib>
#include <future>
#include <map>
#include <string>
#include <mutex>
#include <vector>
#pragma once
using namespace std::string_literals;
template <typename Key, typename Value>
class ConcurrentMap
{
private:
struct Bucket_
{
std::mutex map_mutex_;
std::map<Key, Value> map_;
};
std::vector<Bucket_> buckets_;
public:
static_assert(std::is_integral_v<Key>, "ConcurrentMap supports only integer keys"s);
struct Access
{
Access(const Key& key, Bucket_& bucket)
:value_mutex(bucket.map_mutex_), ref_to_value(bucket.map_[key]) {}
std::lock_guard<std::mutex> value_mutex;
Value& ref_to_value;
};
explicit ConcurrentMap(size_t bucket_count)
:buckets_(bucket_count) {}
void erase(const Key& key)
{
Bucket_& bucket = buckets_[static_cast<uint64_t>(key) % buckets_.size()];
std::lock_guard lock(bucket.map_mutex_);
bucket.map_.erase(key);
}
Access operator[](const Key& key)
{
return { key, buckets_[static_cast<uint64_t>(key) % buckets_.size()] };
}
std::map<Key, Value> BuildOrdinaryMap()
{
std::map<Key, Value> result;
for (auto& [mutex, map] : buckets_)
{
std::lock_guard lock_map(mutex);
result.insert(map.begin(), map.end());
}
return result;
}
};