-
Notifications
You must be signed in to change notification settings - Fork 616
Expand file tree
/
Copy pathregistry.hpp
More file actions
95 lines (74 loc) · 1.7 KB
/
Copy pathregistry.hpp
File metadata and controls
95 lines (74 loc) · 1.7 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
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
#ifndef REGISTRY_H
#define REGISTRY_H
#include "base/i2-base.hpp"
#include "base/atomic.hpp"
#include "base/exception.hpp"
#include "base/string.hpp"
#include "base/singleton.hpp"
#include <shared_mutex>
#include <stdexcept>
#include <unordered_map>
#include <mutex>
namespace icinga
{
/**
* A registry.
*
* @ingroup base
*/
template<typename T>
class Registry
{
public:
typedef std::unordered_map<String, T> ItemMap;
static Registry* GetInstance()
{
return Singleton<Registry>::GetInstance();
}
void Register(const String& name, const T& item)
{
std::unique_lock lock (m_Mutex);
if (m_Frozen) {
BOOST_THROW_EXCEPTION(std::logic_error("Registry is read-only and must not be modified."));
}
m_Items[name] = item;
}
T GetItem(const String& name) const
{
auto lock (ReadLockUnlessFrozen());
auto it = m_Items.find(name);
if (it == m_Items.end())
return T();
return it->second;
}
ItemMap GetItems() const
{
auto lock (ReadLockUnlessFrozen());
return m_Items; /* Makes a copy of the map. */
}
/**
* Freeze the registry, preventing further updates.
*
* This only prevents inserting, replacing or deleting values from the registry.
* This operation has no effect on objects referenced by the values, these remain mutable if they were before.
*/
void Freeze()
{
std::unique_lock lock (m_Mutex);
m_Frozen.store(true);
}
private:
mutable std::shared_mutex m_Mutex;
Atomic<bool> m_Frozen {false};
ItemMap m_Items;
std::shared_lock<std::shared_mutex> ReadLockUnlessFrozen() const
{
if (m_Frozen.load(std::memory_order_relaxed)) {
return {};
}
return std::shared_lock(m_Mutex);
}
};
}
#endif /* REGISTRY_H */