forked from organicmaps/organicmaps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobject_pool.hpp
89 lines (80 loc) · 1.86 KB
/
object_pool.hpp
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
#pragma once
#include "base/assert.hpp"
#include "base/logging.hpp"
#include <list>
#include <mutex>
#include <set>
#include <string>
#define LOG_OBJECT_POOL
namespace dp
{
template<typename T, typename Factory>
class ObjectPool final
{
public:
ObjectPool(int count, Factory const & f)
: m_factory(f)
{
for (int i = 0; i < count; ++i)
{
T *novice = m_factory.GetNew();
#if defined(DEBUG) || defined(LOG_OBJECT_POOL)
m_checkerSet.insert(novice);
#endif
m_pool.push_back(novice);
}
}
~ObjectPool()
{
for (auto it = m_pool.begin(); it != m_pool.end(); it++)
{
T * cur = *it;
#if defined(DEBUG) || defined(LOG_OBJECT_POOL)
auto its = m_checkerSet.find(cur);
static std::string const kMessage = "The same element has been returned twice or more!";
ASSERT(its != m_checkerSet.end(), (kMessage));
if (its == m_checkerSet.end())
LOG(LWARNING, (kMessage));
m_checkerSet.erase(its);
#endif
delete cur;
}
#if defined(DEBUG) || defined(LOG_OBJECT_POOL)
static std::string const kMessage2 = "Not all elements were returned to pool!";
ASSERT(m_checkerSet.empty(), (kMessage2));
if (!m_checkerSet.empty())
LOG(LWARNING, (kMessage2));
#endif
}
T * Get()
{
std::lock_guard<std::mutex> lock(m_lock);
if (m_pool.empty())
{
T * novice = m_factory.GetNew();
#if defined(DEBUG) || defined(LOG_OBJECT_POOL)
m_checkerSet.insert(novice);
#endif
return novice;
}
else
{
T * pt = m_pool.front();
m_pool.pop_front();
return pt;
}
}
void Return(T * object)
{
std::lock_guard<std::mutex> lock(m_lock);
m_pool.push_back(object);
}
private:
#if defined(DEBUG) || defined(LOG_OBJECT_POOL)
std::set<T *> m_checkerSet;
#endif
std::list<T *> m_pool;
Factory m_factory;
std::mutex m_lock;
};
} // namespace dp