-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmassAllocator.h
More file actions
353 lines (297 loc) · 12.3 KB
/
massAllocator.h
File metadata and controls
353 lines (297 loc) · 12.3 KB
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#pragma once
#include <vector>
#include <string>
#include <atomic>
#include <cstdlib>
#include <thread>
/*! \brief Хранилище для объектов с быстрым выделением нового элемента.
*Поддерживаются только операции выделеления нового элемента и полной очистки.
*Тип T не должен иметь конструктора. Элемент инициализируется нулями.
*/
template <typename T>
class MassAllocator
{
public:
typedef size_t size_type ;
typedef T& reference;
typedef const T& const_reference;
typedef T* pointer;
///Конструктор.
MassAllocator(unsigned int blockSize = 1024 * 128);
///Деструктор.
~MassAllocator();
///Создание нового элемента. Возвращается указатель на созданый элемент и его индекс.
pointer createElement(size_type *index = nullptr);
///Возвращает элемент по индексу
reference operator[](size_type index);
///Возвращает элемент по индексу
const_reference operator[](size_type index) const;
///Реализована ли lock-free семантика
bool is_lock_free() const { return curAtomicIndex_.is_lock_free(); }
///Итератор для хранилища.
class Iterator
{
public:
typedef typename std::random_access_iterator_tag iterator_category;
typedef T value_type;
typedef size_t difference_type;
typedef T* pointer;
typedef T& reference;
///Перемещает итератор на следующий элемент хранилища
Iterator& operator++();
Iterator operator++(int);
///Перемещает итератор на предыдущий элемент хранилища
Iterator& operator--();
Iterator operator--(int);
difference_type operator-(const Iterator &rh) const;
Iterator operator-(difference_type offset) const;
Iterator operator+(difference_type offset) const;
///Возвращает указатель на элемент, на котором находится итератор
pointer operator->();
///Возвращает ссылку на элемент, на котором находится итератор
reference operator*();
///Равенство итераторов
bool operator==(const Iterator &rh) const;
///Сравнение итераторов на меньше
bool operator<(const Iterator &rh) const;
///Неравенство итераторов
bool operator!=(const Iterator &rh) const;
///Возвращает индекс элемента, на котором находится итератор
size_type getIndex() const;
private:
friend class MassAllocator;
MassAllocator *MassAllocator_;
size_type index_;
};
///Возвращает итератор на начало хранилища
Iterator begin();
///Возвращает итератор на конец хранилища
Iterator end();
///Kоличество элементов
size_t size() const;
///Очищает хранилище, сбрасывает индекс.
void clear();
///Возвращает потребление памяти
size_t memUse() const;
private:
//Запрет копирования
MassAllocator(const MassAllocator &);
MassAllocator& operator=(const MassAllocator &);
///Количество элементов в блоке.
unsigned int elementsInBlockCount_;
///Блоки с элементами.
std::vector<T*> blocks_; // вектор массивов
///Сквозной индекс для захвата следующего свободного элемента.
///Cтаршие 32 бита это индекс блока, а нижние 32 бита - индекс элемента в блоке.
std::atomic<uint64_t> curAtomicIndex_;
///Задает значение сквозного индекс по номеру блока и индексу в блоке.
void setIndex(unsigned int blockIndx, unsigned int itemIndex);
};
template <typename T>
MassAllocator<T>::MassAllocator(unsigned int blockSize)
: elementsInBlockCount_(blockSize)
{
//задаем значение сквозного индекса таким, чтобы первое выделение элемента привело к распределению нового блока
setIndex(0, elementsInBlockCount_);
}
template <typename T>
MassAllocator<T>::~MassAllocator()
{
clear();
}
template <typename T>
void MassAllocator<T>::setIndex(unsigned int blockIndx, unsigned int itemIndex)
{
auto a = (((uint64_t)blockIndx) << 32) + itemIndex;
curAtomicIndex_.store(a);
}
template <typename T>
typename MassAllocator<T>::pointer MassAllocator<T>::createElement(size_type *returningIndex)
{
//Делаем union для доступа к старшим и младшим 32 битам 64 битного целого
union {
uint64_t index;
struct HiLoParts {
uint32_t itemIndex;
uint32_t blockIndx;
} parts;
};
//получаем новый полный индекс
index = curAtomicIndex_++;
//если индекс элемента в блоке входит в допустимые пределы, то мы быстренько возвращаем индекс и указатель выделенного элемента
if(parts.itemIndex < elementsInBlockCount_)
{
if (returningIndex != nullptr)
*returningIndex = parts.blockIndx * elementsInBlockCount_ + parts.itemIndex;
return &(blocks_[parts.blockIndx][parts.itemIndex]);
}
commitBlock:
if (parts.itemIndex == elementsInBlockCount_)
{
//на нас закончился блок и именно нашему потоку нужно выделить еще один блок памяти
auto bufferSize = elementsInBlockCount_ * sizeof(T);
T* buffer = (T*)malloc(bufferSize);
if (buffer == nullptr)
throw std::bad_alloc();
memset(buffer, 0, bufferSize);
blocks_.push_back(buffer);
//мы забираем себе нулевой элемент в блоке
parts.blockIndx = (unsigned int)(blocks_.size() - 1);
parts.itemIndex = 0;
if (returningIndex != nullptr)
*returningIndex = parts.blockIndx * elementsInBlockCount_ + parts.itemIndex;
//устанавливаем счетчик на первый элемент в блоке
setIndex(parts.blockIndx, 1);
return &(blocks_[parts.blockIndx][parts.itemIndex]);
}
//ждем, пока другой поток производит выделение нового блока
do
{
do
{
// блок еще не выделен, продолжаем ожидание relaxed-чтением
std::this_thread::yield();
index = curAtomicIndex_.load(std::memory_order_relaxed);
} while (parts.itemIndex > elementsInBlockCount_);
//блок был выделен, резервируем элемент
index = curAtomicIndex_++;
} while (parts.itemIndex > elementsInBlockCount_);
if (parts.itemIndex == elementsInBlockCount_)
//нам не повезло, к моменту пока мы очнулись именно на нас закончился блок
goto commitBlock;
//блок был выделен другим потоком, мы захватили валидный индекс элемента из нового блока
if (returningIndex != nullptr)
*returningIndex = parts.blockIndx * elementsInBlockCount_ + parts.itemIndex;
return &(blocks_[parts.blockIndx][parts.itemIndex]);
}
template <typename T>
typename MassAllocator<T>::reference MassAllocator<T>::operator[](size_type index)
{
size_t indexOfBlock = index / elementsInBlockCount_;
size_t indexInBlock = index % elementsInBlockCount_;
return blocks_[indexOfBlock][indexInBlock];
}
template <typename T>
typename MassAllocator<T>::const_reference MassAllocator<T>::operator[](size_type index) const
{
size_t indexOfBlock = index / elementsInBlockCount_;
size_t indexInBlock = index % elementsInBlockCount_;
return blocks_[indexOfBlock][indexInBlock];
}
template <typename T>
typename MassAllocator<T>::Iterator MassAllocator<T>::begin()
{
Iterator result;
result.MassAllocator_ = this;
result.index_ = 0;
return result;
}
template <typename T>
typename MassAllocator<T>::Iterator MassAllocator<T>::end()
{
Iterator result;
result.MassAllocator_ = this;
result.index_ = size();
return result;
}
template <typename T>
size_t MassAllocator<T>::size() const
{
if (blocks_.empty())
return 0;
auto index = curAtomicIndex_.load();
size_t blocksCount = index >> 32;
size_t lastIndexInBlock = index & 0xffffffff;
return blocksCount * elementsInBlockCount_ + lastIndexInBlock;
}
template <typename T>
size_t MassAllocator<T>::memUse() const
{
return blocks_.size() * elementsInBlockCount_ * sizeof(T);
}
template <typename T>
void MassAllocator<T>::clear()
{
//почистить все блоки данных
for(auto ii = blocks_.begin(); ii != blocks_.end(); ++ii)
free(*ii);
blocks_.clear();
//задаем значение сквозного индекса таким, чтобы первое выделение элемента привело к распределению нового блока
setIndex(0, elementsInBlockCount_);
}
//=============================================================================
template <typename T>
typename MassAllocator<T>::Iterator& MassAllocator<T>::Iterator::operator++()
{
++index_;
return *this;
}
template <typename T>
typename MassAllocator<T>::Iterator MassAllocator<T>::Iterator::operator++(int)
{
Iterator result(*this);
++index_;
return result;
}
template <typename T>
typename MassAllocator<T>::Iterator& MassAllocator<T>::Iterator::operator--()
{
--index_;
return *this;
}
template <typename T>
typename MassAllocator<T>::Iterator MassAllocator<T>::Iterator::operator--(int)
{
Iterator result(*this);
--index_;
return result;
}
template <typename T>
typename MassAllocator<T>::Iterator::difference_type MassAllocator<T>::Iterator::operator-(const Iterator &rh) const
{
return index_ - rh.index_;
}
template <typename T>
typename MassAllocator<T>::Iterator MassAllocator<T>::Iterator::operator-(typename MassAllocator<T>::Iterator::difference_type offset) const
{
MassAllocator<T>::Iterator result(*this);
result.index_ -= offset;
return result;
}
template <typename T>
typename MassAllocator<T>::Iterator MassAllocator<T>::Iterator::operator+(typename MassAllocator<T>::Iterator::difference_type offset) const
{
MassAllocator<T>::Iterator result(*this);
result.index_ += offset;
return result;
}
template <typename T>
typename MassAllocator<T>::pointer MassAllocator<T>::Iterator:: operator->()
{
return &(*MassAllocator_)[index_];
}
template <typename T>
typename MassAllocator<T>::reference MassAllocator<T>::Iterator:: operator*()
{
return (*MassAllocator_)[index_];
}
template <typename T>
bool MassAllocator<T>::Iterator::operator==(const Iterator &rh) const
{
return index_ == rh.index_;
}
template <typename T>
bool MassAllocator<T>::Iterator::operator<(const Iterator &rh) const
{
return index_ < rh.index_;
}
template <typename T>
bool MassAllocator<T>::Iterator::operator!=(const Iterator &rh) const
{
return !(*this == rh);
}
template <typename T>
typename MassAllocator<T>::size_type MassAllocator<T>::Iterator::getIndex() const
{
return index_;
}