23 #ifndef MXNET_COMMON_OBJECT_POOL_H_ 24 #define MXNET_COMMON_OBJECT_POOL_H_ 25 #include <dmlc/logging.h> 47 template <
typename... Args>
48 T*
New(Args&&... args);
76 LinkedList* next{
nullptr};
80 LinkedList* next{
nullptr};
89 constexpr
static std::size_t kPageSize = 1 << 12;
95 LinkedList* head_{
nullptr};
99 std::vector<void*> allocated_;
109 void AllocateChunk();
116 template <
typename T>
122 template <
typename... Args>
123 static T*
New(Args&&... args);
130 static void Delete(T* ptr);
133 template <
typename T>
135 for (
auto i : allocated_) {
140 template <
typename T>
141 template <
typename... Args>
145 std::lock_guard<std::mutex> lock{m_};
146 if (head_->next ==
nullptr) {
152 return new (
static_cast<void*
>(ret)) T(std::forward<Args>(args)...);
155 template <
typename T>
158 auto linked_list_ptr =
reinterpret_cast<LinkedList*
>(ptr);
160 std::lock_guard<std::mutex> lock{m_};
161 linked_list_ptr->next = head_;
162 head_ = linked_list_ptr;
166 template <
typename T>
171 template <
typename T>
173 static std::shared_ptr<ObjectPool<T> > inst_ptr(
new ObjectPool<T>());
177 template <
typename T>
182 template <
typename T>
184 static_assert(
sizeof(LinkedList) <= kPageSize,
"Object too big.");
185 static_assert(
sizeof(LinkedList) %
alignof(LinkedList) == 0,
"ObjectPooll Invariant");
186 static_assert(
alignof(LinkedList) %
alignof(T) == 0,
"ObjectPooll Invariant");
187 static_assert(kPageSize %
alignof(LinkedList) == 0,
"ObjectPooll Invariant");
190 new_chunk_ptr = _aligned_malloc(kPageSize, kPageSize);
191 CHECK(new_chunk_ptr != NULL) <<
"Allocation failed";
193 int ret = posix_memalign(&new_chunk_ptr, kPageSize, kPageSize);
194 CHECK_EQ(ret, 0) <<
"Allocation failed";
196 allocated_.emplace_back(new_chunk_ptr);
197 auto new_chunk =
static_cast<LinkedList*
>(new_chunk_ptr);
198 auto size = kPageSize /
sizeof(LinkedList);
199 for (std::size_t i = 0; i < size - 1; ++i) {
200 new_chunk[i].next = &new_chunk[i + 1];
202 new_chunk[size - 1].next = head_;
206 template <
typename T>
207 template <
typename... Args>
212 template <
typename T>
219 #endif // MXNET_COMMON_OBJECT_POOL_H_ static void Delete(T *ptr)
Delete an existing object.
Definition: object_pool.h:213
static T * New(Args &&...args)
Create new object.
Definition: object_pool.h:208
namespace of mxnet
Definition: base.h:89
T * New(Args &&...args)
Create new object.
Definition: object_pool.h:142
static ObjectPool * Get()
Get singleton instance of pool.
Definition: object_pool.h:167
static std::shared_ptr< ObjectPool > _GetSharedRef()
Get a shared ptr of the singleton instance of pool.
Definition: object_pool.h:172
void Delete(T *ptr)
Delete an existing object.
Definition: object_pool.h:156
Helper trait class for easy allocation and deallocation.
Definition: object_pool.h:117
~ObjectPool()
Destructor.
Definition: object_pool.h:134
Object pool for fast allocation and deallocation.
Definition: object_pool.h:37