介绍
SGI STL内存池源码移植要考虑线程安全问题,因为是在容器中使用,这个移植的工作主要就是将SGI STL的二级空间配置器抽取出最小的部分实现我们自己的二级空间配置器myallocator
从而能够应用在容器中
完整代码
// myallocator.h
#include <mutex>
#include <new>
using namespace std;
// 封装malloc和free操作,可以设置OOM释放内存的回调
template<int __inst>
class __malloc_alloc_template
{
private:
static void* _S_oom_malloc(size_t);
static void* _S_oom_realloc(void *,size_t);
static void (*__malloc_alloc_oom_handler)();
public:
static void* allocate(size_t __n)
{
void* __result = malloc(__n);
if (nullptr == __result) __result = _S_oom_malloc(__n);
return __result;
}
static void deallocate(void* __p, size_t)
{
free(__p);
}
static void* reallocate(void* __p, size_t __new_sz)
{
void* __result = realloc(__p, __new_sz);
if (nullptr == __result) __result = _S_oom_realloc(__p, __new_sz);
return __result;
}
// 函数名为__set_malloc_handler
// 返回值类型为void (*)(),即函数指针
// 参数类型为void (*)()
// 功能:设置心得回调函数,返回旧的回调函数
static void (*__set_malloc_handler(void (*__f)()))()
{
void (*__old)() = __malloc_alloc_oom_handler;
__malloc_alloc_oom_handler = __f;
return __old;
}
};
template <int __inst>
void (*__malloc_alloc_template<__inst>::__malloc_alloc_oom_handler)() = nullptr;
template<int __inst>
void* __malloc_alloc_template<__inst>::_S_oom_malloc(size_t __n)
{
void (*__my_malloc_handler)();
void* __result;
for (;;)
{
__my_malloc_handler = __malloc_alloc_oom_handler;
if (nullptr == __my_malloc_handler) { throw bad_alloc(); }
// 有设置处理函数会一直尝试
(*__my_malloc_handler)();
__result = malloc(__n);
if (__result) return (__result);
}
}
template<int __inst>
void* __malloc_alloc_template<__inst>::_S_oom_realloc(void *__p, size_t __n)
{
void (*__my_malloc_handler)();
void* __result;
for (;;)
{
__my_malloc_handler = __malloc_alloc_oom_handler;
if (nullptr == __my_malloc_handler) { throw bad_alloc(); }
// 有设置处理函数会一直尝试
(*__my_malloc_handler)();
__result = realloc(__p, __n);
if (__result) return (__result);
}
}
typedef __malloc_alloc_template<0> malloc_alloc;
//
template<typename T>
class myallocator
{
public:
using value_type = T;
constexpr myallocator() noexcept {}
constexpr myallocator(const myallocator&) noexcept = default;
template <class _Other>
constexpr myallocator(const myallocator<_Other>&) noexcept {}
// 开辟内存
T* allocate(size_t __n)
{
__n = __n * sizeof(T);
void* __ret = 0;
// 超过 _MAX_BYTES ,使用一级空间配置器
if (__n > (size_t)_MAX_BYTES) {
__ret = malloc_alloc::allocate(__n);
}
else {
_Obj* volatile* __my_free_list
= _S_free_list + _S_freelist_index(__n);
std::lock_guard<std::mutex> guard(mtx);
_Obj* __result = *__my_free_list;
if (__result == 0) // 这个内存块链表为空,则创建该chunk块
__ret = _S_refill(_S_round_up(__n));
else {
*__my_free_list = __result->_M_free_list_link;
__ret = __result;
}
}
return (T*)__ret;
}
// 释放内存
void deallocate(void* __p, size_t __n)
{
if (__n > (size_t)_MAX_BYTES)
{
malloc_alloc::deallocate(__p, __n);
}
else
{
_Obj* volatile* __my_free_list = _S_free_list + _S_freelist_index(__n);
_Obj* __q = (_Obj*)__p;
std::lock_guard<std::mutex> guard(mtx);
__q->_M_free_list_link = *__my_free_list;
*__my_free_list = __q;
}
}
// 内存扩容和缩容
void* reallocate(void* __p, size_t __old_sz, size_t __new_sz)
{
void* __result;
size_t __copy_sz;
if (__old_sz > (size_t)_MAX_BYTES && __new_sz > (size_t)_MAX_BYTES)
{
return (realloc(__p, __new_sz)); // 使用C底层提供的内存重分配函数
}
if (_S_round_up(__old_sz) == _S_round_up(__new_sz)) return (__p);
__result = allocate(__new_sz);
__copy_sz = __new_sz > __old_sz ? __old_sz : __new_sz;
memcpy(__result, __p, __copy_sz);
deallocate(__p, __old_sz);
return (__result);
}
// 对象构造
void construct(T* __p, const T& val)
{
new (__p) T(val);
}
// 对象析构
void destroy(T* __p)
{
__p->~T();
}
private:
enum { _ALIGN = 8 }; // 对齐倍数
enum { _MAX_BYTES = 128 }; // 内存池中最大trunk的单位内存
enum { _NFREELISTS = 16 }; // 自由链表(trunk块)个数
// trunk中每一个内存小块的头信息
union _Obj {
union _Obj* _M_free_list_link; // 指向下一个内存小块
char _M_client_data[1];
};
// Chunk allocation state.
static char* _S_start_free;
static char* _S_end_free;
static size_t _S_heap_size;
// 存储trunk块起始小块内存地址的数组
static _Obj* volatile _S_free_list[_NFREELISTS];
// 内存池是基于数组实现,需要考虑线程安全
static std::mutex mtx;
// 将 __bytes上调至 _ALIGN 倍数
static size_t _S_round_up(size_t __bytes)
{
return (((__bytes)+(size_t)_ALIGN - 1) & ~((size_t)_ALIGN - 1));
}
// 获得 __bytes 大小的区块所在的freelist编号
static size_t _S_freelist_index(size_t __bytes)
{
return (((__bytes)+(size_t)_ALIGN - 1) / (size_t)_ALIGN - 1);
}
// 把trunk内分配好的内存小块进行连接
static void* _S_refill(size_t __n)
{
int __nobjs = 20;
char* __chunk = _S_chunk_alloc(__n, __nobjs);
_Obj* volatile* __my_free_list;
_Obj* __result;
_Obj* __current_obj;
_Obj* __next_obj;
int __i;
if (1 == __nobjs) return (__chunk);
__my_free_list = _S_free_list + _S_freelist_index(__n);
// 在trunk块里建立起链表
__result = (_Obj*)__chunk;
*__my_free_list = __next_obj = (_Obj*)(__chunk + __n); // 移动到下一个内存小块
for (__i = 1; ; __i++)
{
__current_obj = __next_obj;
__next_obj = (_Obj*)((char*)__next_obj + __n);
if (__nobjs - 1 == __i)
{
__current_obj->_M_free_list_link = 0;
break;
}
else
{
__current_obj->_M_free_list_link = __next_obj;
}
}
return (__result);
}
static char* _S_chunk_alloc(size_t __size, int& __nobjs)
{
char* __result;
size_t __total_bytes = __size * __nobjs; // 需要的内存大小
size_t __bytes_left = _S_end_free - _S_start_free; // 剩余可用空间大小
if (__bytes_left >= __total_bytes)
{
__result = _S_start_free;
_S_start_free += __total_bytes;
return (__result);
}
else if (__bytes_left >= __size)
{
// 比如需要16字节的内存块,可以从8字节的内存块链表的备用部分取用
// 即16字节的内存块链表起始地址指向8字节的内存块链表中的后备块
// 剩余可用空间大小 < 需要的内存大小 但是 > 所需要的单个内存块的大小
__nobjs = (int)(__bytes_left / __size); // 计算能转换成目标内存小块的数量
__total_bytes = __size * __nobjs;
__result = _S_start_free;
_S_start_free += __total_bytes;
return (__result);
}
else
{
size_t __bytes_to_get = 2 * __total_bytes + _S_round_up(_S_heap_size >> 4);
if (__bytes_left > 0) // 内存碎片处理,接到对应free_list的头部
{
_Obj* volatile* _my_free_list = _S_free_list + _S_freelist_index(__bytes_left);
((_Obj*)_S_start_free)->_M_free_list_link = *_my_free_list; // 头插
*_my_free_list = (_Obj*)_S_start_free;
}
// 分配内存
_S_start_free = (char*)malloc(__bytes_to_get);
if (nullptr == _S_start_free)
{
size_t __i;
_Obj* volatile* __my_free_list;
_Obj* __p;
for (__i = __size;
__i <= (size_t)_MAX_BYTES;
__i += (size_t)_ALIGN)
{
__my_free_list = _S_free_list + _S_freelist_index(__i);
__p = *__my_free_list;
if (nullptr != __p)
{
*__my_free_list = __p->_M_free_list_link;
_S_start_free = (char*)__p;
_S_end_free = _S_start_free + __i;
return (_S_chunk_alloc(__size, __nobjs));
}
}
// 异常情况
_S_end_free = 0;
_S_start_free = (char*)malloc_alloc::allocate(__bytes_to_get);
}
_S_heap_size += __bytes_to_get;
_S_end_free = _S_start_free + __bytes_to_get;
return (_S_chunk_alloc(__size, __nobjs));
}
}
};
// 静态成员类外初始化
template <typename T>
char* myallocator<T>::_S_start_free = nullptr;
template <typename T>
char* myallocator<T>::_S_end_free = nullptr;
template <typename T>
size_t myallocator<T>::_S_heap_size = 0;
template <typename T>
typename myallocator<T>::_Obj* volatile myallocator<T>::_S_free_list[_NFREELISTS] =
{ nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
template <typename T>
std::mutex myallocator<T>::mtx;
测试
#include "myallocator.h"
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int, myallocator<int>> vec;
srand((unsigned int)time(NULL));
for (int i = 0; i < 10; ++i)
{
vec.push_back(rand() % 1000);
}
for (int n : vec)
{
cout << n << " " << endl;
}
return 0;
}
实验结果
一些问题
vector
在容量分配时调用myallocator::allocate
传入的参数是对象的个数,而非内存大小,查看vector::reserve
函数的调用可以看出传入的是元素个数,而不是字节大小:
所以在myallocator::allocate
内要将__n设置为实际的内存大小即 __n = __n * sizeof(T)
,否则会出现如下非法数字的情况
因为用1B来存4B的内容了