4 #ifndef MXNET_COMMON_OBJECT_POOL_H_
5 #define MXNET_COMMON_OBJECT_POOL_H_
6 #include <dmlc/logging.h>
28 template <
typename... Args>
29 T*
New(Args&&... args);
57 LinkedList* next{
nullptr};
61 LinkedList* next{
nullptr};
70 constexpr
static std::size_t kPageSize = 1 << 12;
76 LinkedList* head_{
nullptr};
80 std::vector<void*> allocated_;
103 template <
typename... Args>
104 static T*
New(Args&&... args);
111 static void Delete(T* ptr);
114 template <
typename T>
122 template <
typename T>
123 template <
typename... Args>
127 std::lock_guard<std::mutex> lock{m_};
128 if (head_->next ==
nullptr) {
134 return new (
static_cast<void*
>(ret)) T(std::forward<Args>(args)...);
137 template <
typename T>
140 auto linked_list_ptr =
reinterpret_cast<LinkedList*
>(ptr);
142 std::lock_guard<std::mutex> lock{m_};
143 linked_list_ptr->next = head_;
144 head_ = linked_list_ptr;
148 template <
typename T>
150 return _GetSharedRef().get();
153 template <
typename T>
155 static std::shared_ptr<ObjectPool<T> > inst_ptr(
new ObjectPool<T>());
159 template <
typename T>
164 template <
typename T>
165 void ObjectPool<T>::AllocateChunk() {
166 static_assert(
sizeof(LinkedList) <= kPageSize,
"Object too big.");
167 static_assert(
sizeof(LinkedList) %
alignof(LinkedList) == 0,
"ObjectPooll Invariant");
168 static_assert(
alignof(LinkedList) %
alignof(T) == 0,
"ObjectPooll Invariant");
169 static_assert(kPageSize %
alignof(LinkedList) == 0,
"ObjectPooll Invariant");
172 new_chunk_ptr = _aligned_malloc(kPageSize, kPageSize);
173 CHECK_NE(new_chunk_ptr, NULL) <<
"Allocation failed";
175 int ret = posix_memalign(&new_chunk_ptr, kPageSize, kPageSize);
176 CHECK_EQ(ret, 0) <<
"Allocation failed";
178 allocated_.emplace_back(new_chunk_ptr);
179 auto new_chunk =
static_cast<LinkedList*
>(new_chunk_ptr);
180 auto size = kPageSize /
sizeof(LinkedList);
181 for (std::size_t i = 0; i < size - 1; ++i) {
182 new_chunk[i].next = &new_chunk[i + 1];
184 new_chunk[size - 1].next = head_;
188 template <
typename T>
189 template <
typename... Args>
194 template <
typename T>
201 #endif // MXNET_COMMON_OBJECT_POOL_H_
static void Delete(T *ptr)
Delete an existing object.
Definition: object_pool.h:195
static T * New(Args &&...args)
Create new object.
Definition: object_pool.h:190
T * New(Args &&...args)
Create new object.
Definition: object_pool.h:124
static ObjectPool * Get()
Get singleton instance of pool.
Definition: object_pool.h:149
static std::shared_ptr< ObjectPool > _GetSharedRef()
Get a shared ptr of the singleton instance of pool.
Definition: object_pool.h:154
void Delete(T *ptr)
Delete an existing object.
Definition: object_pool.h:138
Helper trait class for easy allocation and deallocation.
Definition: object_pool.h:98
~ObjectPool()
Destructor.
Definition: object_pool.h:115
Object pool for fast allocation and deallocation.
Definition: object_pool.h:18