13 * The BLOCK_STEP at least should be sizeof(void*).
14 * It means on amd64 the min step is 8, while on i386 the min step is 4.
16 template<int BLOCK_STEP
= 8, int BLOCK_COUNT
= 16>
19 explicit MemPool(int secCount
= 1024):
35 for (int i
= 0; i
< BLOCK_COUNT
; ++i
) {
36 mFreeBlocks
[i
] = NULL
;
42 * If the size is large than the max block size,<br/>
43 * we'll directly use malloc(). <br/>
44 * So the potential problem is: <br/>
45 * you should always remember to call Reuse() to free such memory, <br/>
46 * as such memory won't be record in mMemList(so, it won't be freed by Free()/dtor).
48 void* Alloc(size_t size
)
50 size
= SCX_ALIGN(size
, BLOCK_STEP
);
51 int index
= (size
-1)/BLOCK_STEP
;
52 if (index
< BLOCK_COUNT
) {
53 if (mFreeBlocks
[index
] == NULL
) {
55 std::cout
<< "." << std::flush
;
57 size_t total
= sizeof(Mem
) + mSecCount
*size
;
58 Mem
* mem
= (Mem
*)malloc(total
);
59 mem
->buf
= (char*)mem
+ sizeof(Mem
);
63 Sec
* sec
= (Sec
*)mMemList
->buf
;
64 mFreeBlocks
[index
] = sec
;
65 for (int i
= 0; i
< mSecCount
-1; ++i
) {
66 sec
->next
= (Sec
*)((char*)sec
+size
);
71 Sec
* sec
= mFreeBlocks
[index
];
72 mFreeBlocks
[index
] = sec
->next
;
76 std::cout
<< "!" << size
<< std::flush
;
83 void Reuse(void* p
, int size
)
85 size
= SCX_ALIGN(size
, BLOCK_STEP
);
86 int index
= (size
-1)/BLOCK_STEP
;
87 if (index
< BLOCK_COUNT
) {
89 sec
->next
= mFreeBlocks
[index
];
90 mFreeBlocks
[index
] = sec
;
97 * Free all the memory we've allocated.
101 for (Mem
* mem
= mMemList
; mMemList
!= NULL
; mem
= mMemList
) {
102 mMemList
= mem
->next
;
110 * The pool size means how many bytes we've allocated,<br/>
111 * not the available size for Alloc() before next allocation.
118 void SetSecCount(int secCount
)
120 mSecCount
= secCount
;
123 int GetSecCount() const
128 void PreAlloc(size_t size
)
148 Sec
* mFreeBlocks
[BLOCK_COUNT
];