-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemory_Pool.cpp
More file actions
292 lines (253 loc) · 9.1 KB
/
Copy pathMemory_Pool.cpp
File metadata and controls
292 lines (253 loc) · 9.1 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
#include <iostream>
#include <vector>
#include <array>
#include <cstddef>
#include <cassert>
#include <atomic>
#include <mutex>
#include <new>
#include <string>
#include <optional>
#include <functional>
// ============================================================================
// 1. 对齐工具
// ============================================================================
inline std::size_t align_up(std::size_t size, std::size_t alignment) noexcept {
return (size + alignment - 1) & ~(alignment - 1);
}
// ============================================================================
// 2. LockFreeStack — 无锁 Treiber Stack (节点放内存块头部)
// ============================================================================
struct FreeNode {
FreeNode* next;
};
class LockFreeStack {
public:
void Push(void* ptr) noexcept {
auto* node = static_cast<FreeNode*>(ptr);
FreeNode* head = head_.load(std::memory_order_relaxed);
do {
node->next = head;
} while (!head_.compare_exchange_weak(
head, node, std::memory_order_release, std::memory_order_relaxed));
}
void* Pop() noexcept {
FreeNode* head = head_.load(std::memory_order_acquire);
while (head) {
FreeNode* next = head->next;
if (head_.compare_exchange_weak(
head, next, std::memory_order_acquire, std::memory_order_relaxed)) {
return head;
}
}
return nullptr;
}
bool Empty() const noexcept { return head_.load(std::memory_order_acquire) == nullptr; }
private:
std::atomic<FreeNode*> head_{nullptr};
};
// ============================================================================
// 3. FixedSizeMemoryPool — 单尺寸内存池
// ============================================================================
class FixedSizeMemoryPool {
public:
FixedSizeMemoryPool(std::size_t block_size, std::size_t blocks_per_chunk = 256)
: block_size_(std::max(block_size, sizeof(FreeNode)))
, blocks_per_chunk_(blocks_per_chunk) {}
~FixedSizeMemoryPool() {
for (char* page : chunks_) { ::operator delete[](page); }
}
void* Allocate() {
void* ptr = free_list_.Pop();
if (!ptr) {
Expand();
ptr = free_list_.Pop();
}
return ptr;
}
void Deallocate(void* ptr) noexcept {
if (ptr) free_list_.Push(ptr);
}
std::size_t BlockSize() const noexcept { return block_size_; }
std::size_t ChunkCount() const noexcept { return chunks_.size(); }
private:
void Expand() {
std::size_t bytes = block_size_ * blocks_per_chunk_;
char* page = static_cast<char*>(::operator new[](bytes));
{
std::lock_guard lock(mtx_);
chunks_.push_back(page);
}
for (std::size_t i = 0; i < blocks_per_chunk_; ++i) {
free_list_.Push(page + i * block_size_);
}
}
LockFreeStack free_list_;
std::vector<char*> chunks_;
std::size_t block_size_;
std::size_t blocks_per_chunk_;
std::mutex mtx_;
};
// ============================================================================
// 4. SlabAllocator — 多尺寸 Slab 分配器 (libumem 风格)
// ============================================================================
class SlabAllocator {
struct Slab {
std::size_t block_size;
std::size_t blocks_per_chunk;
std::vector<char*> chunks;
LockFreeStack free_list;
std::mutex mtx;
};
static constexpr std::size_t kMaxSlabSize = 4096;
static constexpr std::size_t kSlabCount = 8;
static constexpr std::array<std::size_t, kSlabCount> kSizes = {
16, 32, 64, 128, 256, 512, 1024, 4096
};
public:
SlabAllocator() {
for (std::size_t i = 0; i < kSlabCount; ++i) {
slabs_[i].block_size = kSizes[i];
slabs_[i].blocks_per_chunk = std::max<std::size_t>(1, kMaxSlabSize / kSizes[i]);
}
}
void* Allocate(std::size_t size) noexcept {
auto idx = IndexFor(size);
if (!idx) return nullptr;
auto& slab = slabs_[*idx];
void* ptr = slab.free_list.Pop();
if (!ptr) {
std::lock_guard lock(slab.mtx);
// 双重检查
ptr = slab.free_list.Pop();
if (!ptr) {
std::size_t bytes = slab.block_size * slab.blocks_per_chunk;
char* page = static_cast<char*>(::operator new[](bytes));
slab.chunks.push_back(page);
for (std::size_t i = 0; i < slab.blocks_per_chunk; ++i) {
slab.free_list.Push(page + i * slab.block_size);
}
ptr = slab.free_list.Pop();
}
}
return ptr;
}
void Deallocate(void* ptr, std::size_t size) noexcept {
if (!ptr) return;
auto idx = IndexFor(size);
if (!idx) return;
slabs_[*idx].free_list.Push(ptr);
}
private:
std::optional<std::size_t> IndexFor(std::size_t size) const noexcept {
for (std::size_t i = 0; i < kSlabCount; ++i) {
if (size <= kSizes[i]) return i;
}
return std::nullopt;
}
std::array<Slab, kSlabCount> slabs_;
};
// ============================================================================
// 5. 线程局部缓存 (TLS batch cache) — 减少跨核 CAS 竞争
// ============================================================================
class TlsCache {
static constexpr std::size_t kBatchSize = 16;
public:
// parent_pool 是 "尺寸已经选好" 的具体池,如 FixedSizeMemoryPool 或 SlabAllocator
using AllocFn = std::function<void*()>;
using FreeFn = std::function<void(void*)>;
TlsCache(AllocFn alloc, FreeFn free)
: alloc_(std::move(alloc)), free_(std::move(free)) {}
void* Get() {
if (cache_.empty()) Refill();
void* p = cache_.back();
cache_.pop_back();
return p;
}
void Put(void* ptr) {
if (cache_.size() >= kBatchSize) Flush();
cache_.push_back(ptr);
}
~TlsCache() { Flush(); }
private:
void Refill() {
for (std::size_t i = 0; i < kBatchSize; ++i) {
void* p = alloc_();
if (!p) break;
cache_.push_back(p);
}
}
void Flush() {
for (void* p : cache_) free_(p);
cache_.clear();
}
AllocFn alloc_;
FreeFn free_;
std::vector<void*> cache_;
};
// ============================================================================
// 6. 演示
// ============================================================================
struct Particle {
float x, y, z;
int life;
void update() { ++life; }
};
// 全局内存池用于 Particle
static FixedSizeMemoryPool gParticlePool(sizeof(Particle), 2000);
// 仅作为演示,不建议在生产中全局替换 operator new
// 实际项目中请使用工厂函数或自定义 allocator
// 工厂函数代替全局 operator new,更安全清晰
inline Particle* MakeParticle(float x, float y, float z, int life) {
auto* ptr = static_cast<Particle*>(gParticlePool.Allocate());
new (ptr) Particle{x, y, z, life};
return ptr;
}
inline void ReleaseParticle(Particle* p) {
if (p) {
p->~Particle();
gParticlePool.Deallocate(p);
}
}
int main() {
// ---- 演示 FixedSizeMemoryPool ----
{
std::cout << "=== FixedSizeMemoryPool (Particle) ===" << std::endl;
std::vector<Particle*> particles;
for (int i = 0; i < 100'000; ++i) {
particles.push_back(MakeParticle(1.0f, 2.0f, 3.0f, i));
}
for (auto* p : particles) ReleaseParticle(p);
std::cout << " Block size: " << gParticlePool.BlockSize()
<< " bytes, chunks: " << gParticlePool.ChunkCount() << std::endl;
}
// ---- 演示 SlabAllocator ----
{
std::cout << "\n=== SlabAllocator ===" << std::endl;
SlabAllocator slab;
std::vector<std::pair<void*, std::size_t>> allocs;
allocs.emplace_back(slab.Allocate(12), 12); // → 16B slab
allocs.emplace_back(slab.Allocate(120), 120); // → 128B slab
allocs.emplace_back(slab.Allocate(512), 512); // → 512B slab
allocs.emplace_back(slab.Allocate(1024), 1024);//→ 1024B slab
allocs.emplace_back(slab.Allocate(4000), 4000);//→ 4096B slab
for (auto [p, s] : allocs) {
slab.Deallocate(p, s);
}
std::cout << " SlabAllocator alloc/free OK" << std::endl;
}
// ---- 演示 TlsCache ----
{
std::cout << "\n=== TlsCache (batch) ===" << std::endl;
FixedSizeMemoryPool smallPool(32, 64);
TlsCache cache(
[&]() { return smallPool.Allocate(); },
[&](void* p) { smallPool.Deallocate(p); });
std::vector<void*> ptrs;
for (int i = 0; i < 100; ++i) ptrs.push_back(cache.Get());
for (void* p : ptrs) cache.Put(p);
std::cout << " TlsCache batch alloc/free OK" << std::endl;
}
std::cout << "\nAll memory pools OK." << std::endl;
return 0;
}