-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConcurrentMap.h
61 lines (54 loc) · 1.77 KB
/
ConcurrentMap.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
#pragma once
#include <map>
#include <mutex>
#include <shared_mutex>
/*
Very simple header only implementation of a ConcurrentMap.
Use "safe" variants of methods when performing concurrent operations.
Acquire a shared_lock for thread safe iterration.
Acquire a unique_lock if you want to iterate and delete
*/
template<typename key, typename value>
class ConcurrentMap : public std::map<key, value>
{
public:
/*Thread safe insert operation. Acquires unique lock.*/
void safeInsert(std::pair<key, value> element)
{
std::unique_lock<std::shared_mutex> lg(lock);
std::map<key,value>::insert(element);
}
/*Thread safe erase operation. Acquires unique lock.*/
void safeErase(key k)
{
std::unique_lock<std::shared_mutex> lg(lock);
std::map<key, value>::erase(k);
}
/*Thread safe erase operation. Acquires unique lock.*/
void safeErase(typename std::map<key, value>::iterator it)
{
std::unique_lock<std::shared_mutex> lg(lock);
std::map<key, value>::erase(it);
}
/*Thread safe find operation. Acquires shared lock.*/
std::map<key,value>::iterator safeFind(key k)
{
std::shared_lock<std::shared_mutex> lg(lock);
return std::map<key, value>::find(k);
}
/*Returns a shared lock for the given map.
This lock will provide the executing thread shared read access, and block SafeErrase + SafeInsert in other threads.
Acquire this lock before iterating through the map.*/
std::shared_lock<std::shared_mutex> getSharedLock()
{
return std::shared_lock<std::shared_mutex>(lock);
}
/*Returns a unique lock for the given map.
This lock will provide the executing thread exclusive access to the map until it goes out of scope.*/
std::shared_lock<std::shared_mutex> getUniqueLock()
{
return std::shared_lock<std::shared_mutex>(lock);
}
private:
std::shared_mutex lock;
};