Brief introduction
STL's __pool_alloc, __mt_alloc,boost's Pool series, Ace's ace_cached_allocator are fixed-length memory pools.
Description
The memory pool, depending on whether the length of the stored element is variable, is divided into a variable length, with a fixed length of two memory pools.
Logically, a fixed-length memory pool simply stores elements of the same size, so there is no need to spend extra space (data structures) to store information about the length of the element.
The above several fixed-length memory pools can deal with the problem of frequent allocation of fixed-length memory.
Stl--pool_alloc
Pool_alloc, the principle is to hang up 16 linked lists (_s_free_list), each of which stores data that allocates a size of [1,8],[9-16],[17-24],..., [120,128].
1. (Figure I) is a data structure:
1 class__pool_alloc_base
2{
3 protected:
4
5 enum{_s_align = 8};
6 enum{_s_max_bytes = -};
7 enum{_s_free_list_size = (size_t) _s_max_bytes/(size_t) _s_align};
8
9Union _obj
Ten{
OneUnion _obj* _m_free_list_link;
A Char_m_client_data[ 1]; // The client sees this.
- };
-
the Static_obj* volatile_s_free_list[_s_free_list_size];
-
- // Chunk allocation state.
- Static Char* _S_START_FREE;
+ Static Char* _S_END_FREE;
- Staticsize_t _s_heap_size;
+
A...
at};
2. (figure II) for the linked list:
3.allocate
__pool_alloc<_tp>::allocate (size_type __n, const void*)
Allocate, the function calculates the requested __n multiplied by sizeof (T), deciding which list to allocate.
4.deallocate
__pool_alloc<_tp>::d eallocate (pointer __p, Size_type __n)
This is a key point to note, and __n must be transmitted. If the value of __n is inconsistent with the size of the allocate assignment, it will cause deallocate to fail. The reason is that __pool_alloc does not save the actual element for how long, and he needs to calculate according to __n to which list the data is stored.
Stl--mt_alloc
Mt_alloc implementation is relatively complex, I have a local detailed documentation, but for the reasons of space, not suitable for this article to add.
Definition
template<typename _tp,
typename _poolp = __common_pool_policy< __pool, __ thread_default> >
class __mt_alloc:public __mt_alloc_base<_tp>
Description
Allocate and deallocate are actually using __pool to allocate and manage memory.
Memory pool--fixed-length memory pool