7 #ifndef MXNET_COMMON_LAZY_ALLOC_ARRAY_H_
8 #define MXNET_COMMON_LAZY_ALLOC_ARRAY_H_
10 #include <dmlc/logging.h>
19 template<
typename TElem>
28 template<
typename FCreate>
29 inline TElem*
Get(
int index, FCreate creator);
34 template<
typename FVisit>
35 inline void ForEach(FVisit fvisit);
41 static constexpr std::size_t kInitSize = 16;
43 std::mutex create_mutex_;
45 std::array<std::unique_ptr<TElem>, kInitSize> head_;
47 std::vector<std::unique_ptr<TElem> > more_;
51 template<
typename TElem>
52 template<
typename FCreate>
55 size_t idx =
static_cast<size_t>(index);
56 if (idx < kInitSize) {
57 TElem *ptr = head_[idx].get();
61 std::lock_guard<std::mutex> lock(create_mutex_);
62 TElem *ptr = head_[idx].get();
63 if (ptr !=
nullptr)
return ptr;
64 head_[idx].reset(ptr = creator());
68 std::lock_guard<std::mutex> lock(create_mutex_);
70 if (more_.size() <= idx) more_.resize(idx + 1);
71 TElem *ptr = more_[idx].get();
72 if (ptr !=
nullptr)
return ptr;
73 more_[idx].reset(ptr = creator());
78 template<
typename TElem>
80 std::lock_guard<std::mutex> lock(create_mutex_);
81 for (
size_t i = 0; i < head_.size(); ++i) {
82 head_[i].reset(
nullptr);
84 for (
size_t i = 0; i < more_.size(); ++i) {
85 more_[i].reset(
nullptr);
89 template<
typename TElem>
90 template<
typename FVisit>
92 std::lock_guard<std::mutex> lock(create_mutex_);
93 for (
size_t i = 0; i < head_.size(); ++i) {
94 if (head_[i].
get() !=
nullptr) {
95 fvisit(i, head_[i].
get());
98 for (
size_t i = 0; i < more_.size(); ++i) {
99 if (more_[i].
get() !=
nullptr) {
100 fvisit(i + kInitSize, more_[i].
get());
106 #endif // MXNET_COMMON_LAZY_ALLOC_ARRAY_H_
TElem * Get(int index, FCreate creator)
Get element of corresponding index, if it is not created create by creator.
Definition: lazy_alloc_array.h:53
void Clear()
clear all the allocated elements in array
Definition: lazy_alloc_array.h:79
void ForEach(FVisit fvisit)
for each not null element of the array, call fvisit
Definition: lazy_alloc_array.h:91
Definition: lazy_alloc_array.h:20