Skip to content

Commit a593690

Browse files
committed
doc: complete readme
1 parent 4506c93 commit a593690

File tree

4 files changed

+87
-1
lines changed

4 files changed

+87
-1
lines changed

README.md

Lines changed: 87 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,87 @@
1-
# WW-Memory-Pool
1+
# WW-Memory-Pool
2+
3+
该项目是`WW`系列中,作为学习用途的内存池库
4+
5+
## 特点
6+
7+
+ 采用`tcmalloc`的三层缓存架构,提高内存的分配效率
8+
9+
+ C++11风格,代码易读性强
10+
11+
## 结构
12+
13+
采用三层缓存的结构,其中
14+
15+
+ 页缓存`PageCahce`: 管理整片页段的缓存,负责从系统中获取整页内存,将其切片成小块页段提供给中心缓存
16+
17+
+ 中心缓存`CentralCache`: 管理批量的小块内存,负责从页缓存中获取小块内存,并批量提供给线程缓存
18+
19+
+ 线程缓存`ThreadCache`: 管理少量的小块内存,负责从中心缓存中获取小块内存,并提供给应用程序使用
20+
21+
### 页缓存`PageCahce`
22+
23+
页缓存以页为单位管理内存,在中心缓存申请内存时,页缓存挑选合适的页段,然后将其切片成小块页段提供给中心缓存
24+
25+
![page_cache](doc/img/page_cache.png)
26+
27+
### 中心缓存`CentralCache`
28+
29+
中心缓存从页缓存中获取合适大小的页段,然后根据需要的内存块大小,切割为一定数量的内存块,挂载到一个内存块链表上,供线程缓存使用
30+
31+
![central_cache](doc/img/central_cache.png)
32+
33+
### 线程缓存`ThreadCache`
34+
35+
线程缓存从中心缓存中批量获取内存块,供应用程序申请使用
36+
37+
![thread_cache](doc/img/thread_cache.png)
38+
39+
## 使用
40+
41+
### 直接使用
42+
43+
直接操作线程缓存实例,示例见[threadcache_test.cpp](test/src/threadcache_test.cpp)
44+
45+
```cpp
46+
#include <ThreadCache.h>
47+
48+
int main()
49+
{
50+
// 获取线程缓存实例
51+
WW::ThreadCache & thread_cache = WW::ThreadCache::getThreadCache();
52+
// 申请8字节内存
53+
void * ptr = thread_cache.allocate(8);
54+
// 使用内存
55+
int * p = new(ptr) int(42);
56+
// 归还内存
57+
thread_cache.deallocate(ptr, 8);
58+
59+
return 0;
60+
}
61+
```
62+
63+
### 封装使用
64+
65+
将内存池封装为分配器等,示例见[memory_test.cpp](test/src/memory_test.cpp)
66+
67+
```cpp
68+
pointer allocate(size_type n, const void * hint = nullptr)
69+
{
70+
(void)hint;
71+
if (n > max_size())
72+
throw std::bad_array_new_length();
73+
74+
if (n == 0)
75+
return nullptr;
76+
77+
return static_cast<pointer>(thread_cache.allocate(n * sizeof(T)));
78+
}
79+
80+
void deallocate(pointer ptr, size_type n)
81+
{
82+
if (ptr == nullptr)
83+
return;
84+
85+
thread_cache.deallocate(ptr, n * sizeof(T));
86+
}
87+
```

doc/img/central_cache.png

56.7 KB
Loading

doc/img/page_cache.png

51.7 KB
Loading

doc/img/thread_cache.png

51.2 KB
Loading

0 commit comments

Comments
 (0)