-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_pool.cc
More file actions
70 lines (60 loc) · 1.54 KB
/
Copy pathmemory_pool.cc
File metadata and controls
70 lines (60 loc) · 1.54 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
// Copyright 2024 JOK Inc. All Rights Reserved.
// Author: easytojoin@163.com (jok)
#include <iostream>
#include <list>
#include <mutex> // NOLINT
template <typename T, std::size_t PoolSize = 100>
class MemoryPool {
public:
MemoryPool() { expandPool(); }
~MemoryPool() {
std::unique_lock<std::mutex> lock(mutex_);
for (auto& chunk : pool_) {
delete[] reinterpret_cast<char*>(chunk);
}
}
T* alloc() {
std::unique_lock<std::mutex> lock(mutex_);
if (free_chunks_.empty()) {
expandPool();
}
T* ptr = free_chunks_.front();
free_chunks_.pop_front();
return ptr;
}
void dealloc(T* ptr) {
std::unique_lock<std::mutex> lock(mutex_);
free_chunks_.push_back(ptr);
}
std::size_t getFreeChunksCount() const {
std::unique_lock<std::mutex> lock(mutex_);
return free_chunks_.size();
}
std::size_t getUsedChunksCount() const {
std::unique_lock<std::mutex> lock(mutex_);
return PoolSize - getFreeChunksCount();
}
private:
void expandPool() {
char* blocks = new char[sizeof(T) * PoolSize];
for (std::size_t i = 0; i < PoolSize; i++) {
free_chunks_.push_back(reinterpret_cast<T*>(blocks + i * sizeof(T)));
}
pool_.push_back(blocks);
}
private:
mutable std::mutex mutex_;
std::list<T*> free_chunks_;
std::list<char*> pool_;
};
struct DataObject {
int data[100];
};
int main(int argc, char** argv) {
MemoryPool<DataObject> pool;
DataObject* obj1 = pool.alloc();
DataObject* obj2 = pool.alloc();
pool.dealloc(obj1);
pool.dealloc(obj2);
return 0;
}