-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_pool.h
More file actions
67 lines (50 loc) · 1.77 KB
/
memory_pool.h
File metadata and controls
67 lines (50 loc) · 1.77 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
//
// Created by wnc on 2025/9/15.
//
#ifndef MEMORY_POOL_MEMORY_POOL_H
#define MEMORY_POOL_MEMORY_POOL_H
#include <vector>
#include <unordered_map>
#include <cstddef>
#include <string>
#include <thread>
#include <mutex>
#include <utility> // for std::pair
struct AllocationInfo {
std::string file;
int line;
std::string func;
std::thread::id tid;
bool in_use;
};
class MemoryPool {
public:
MemoryPool(size_t block_size, size_t block_count);
~MemoryPool();
MemoryPool(const MemoryPool&) = delete;
MemoryPool& operator=(const MemoryPool&) = delete;
MemoryPool(MemoryPool&& other) noexcept;
MemoryPool& operator=(MemoryPool&& other) noexcept;
// 用户请求大小会由 MemoryPoolCtr 根据 block_size 选择
void* allocate(const char* file, int line, const char* func);
void deallocate(void* ptr);
void reportLeaks() const;
// 判断指针是否属于该内存池管理的内存(用于 cvFree 查找)
bool owns(void* ptr) const;
size_t getBlockSize() const { return block_size_; }
size_t getPoolCapacity() const { return capacity_; }
private:
size_t block_size_;
size_t block_count_;
size_t capacity_ = 0;
std::vector<void*> free_list_;
// 将 big_blocks_ 改为 (base, size) 对,方便判断 ptr 是否属于该块
std::vector<std::pair<void*, size_t>> big_blocks_; // 保存每次分配的大块起始地址及字节长度
std::unordered_map<void*, AllocationInfo> allocations_;
mutable std::mutex mtx_; // 线程安全,mutable 以便 const 方法也能加锁
void expandPool(size_t count);
};
// 宏简化调用
#define MP_ALLOC(pool, size) (pool).allocate(__FILE__, __LINE__, __func__)
#define MP_FREE(pool, ptr) (pool).deallocate(ptr)
#endif //MEMORY_POOL_MEMORY_POOL_H