-
Notifications
You must be signed in to change notification settings - Fork 0
/
object_cache.h
142 lines (123 loc) · 2.1 KB
/
object_cache.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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#ifndef _MDB_OBJECT_CACHE_H
#define _MDB_OBJECT_CACHE_H
#include <pthread.h>
#include <vector>
namespace mdb {
template<class T>
class CNormalConstructor
{
public:
void construct(T &obj) const
{
}
void destroy(T &obj) const
{
}
void init(T &obj) const
{
new(&obj) T();
}
void deinit(T &obj) const
{
obj.~T();
}
};
template<class T>
class CCacheConstructor
{
public:
void construct(T &obj) const
{
new(&obj)T;
}
void destroy(T &obj) const
{
obj.~T();
}
void init(T &obj) const
{
obj.init();
}
void deinit(T &obj) const
{
obj.deinit();
}
};
template <class T, muint4 MAX_VOLUME = 256, class CConstructor = CNormalConstructor<T> >
class CObjectCache
{
private:
typedef std::vector<T *> CCache;
private:
static void destroy(void *p)
{
CConstructor constructor;
CCache *cache = (CCache *)p;
for (auto iter = cache->begin(), end = cache->end(); iter != end; ++iter)
{
constructor.destroy(**iter);
free(*iter);
}
delete cache;
}
public:
CObjectCache()
{
const mint4 ret = pthread_key_create(&m_threadKey, &destroy);
assert(0 == ret);
}
~CObjectCache()
{
pthread_key_delete(m_threadKey);
}
T *alloc()
{
void *p = pthread_getspecific(m_threadKey);
if (!p)
{
p = new CCache();
assert(p != NULL);
pthread_setspecific(m_threadKey, p);
}
CCache &cache = *( (CCache *)(p));
if (cache.empty())
{
T *pobj = (T *)malloc(sizeof(T));
m_constructor.construct(*pobj);
m_constructor.init(*pobj);
return pobj;
}
T *obj = cache.back();
cache.pop_back();
m_constructor.init(*obj);
return obj;
}
void release(T *obj)
{
void *p = pthread_getspecific(m_threadKey);
if (!p)
{
m_constructor.deinit(*obj);
m_constructor.destroy(*obj);
free((void *)obj);
return;
}
CCache &cache = *((CCache *)(p));
if (cache.size() >= MAX_VOLUME)
{
m_constructor.deinit(*obj);
m_constructor.destroy(*obj);
free((void *)obj);
}
else
{
m_constructor.deinit(*obj);
cache.push_back(obj);
}
}
private:
pthread_key_t m_threadKey;
CConstructor m_constructor;
};
} // namespace mdb
#endif // _MDB_OBJECT_CACHE_H