当前位置:网站首页>剖析SGI STL空间配置器(allocate内存分配函数)
剖析SGI STL空间配置器(allocate内存分配函数)
2022-07-30 07:38:00 【刚入门的代码spa技师】
剖析SGI STL空间配置器(allocate内存分配函数)
要理解allocate函数是如何分配内存,就要先知道他是怎么管理内存的。
allocate函数的定义如下:
/* __n must be > 0 */
static void* allocate(size_t __n)
{
void* __ret = 0;
if (__n > (size_t) _MAX_BYTES) {
__ret = malloc_alloc::allocate(__n);
}
else {
_Obj* __STL_VOLATILE* __my_free_list
= _S_free_list + _S_freelist_index(__n);
// Acquire the lock here with a constructor call.
// This ensures that it is released in exit or during stack
// unwinding.
# ifndef _NOTHREADS
/*REFERENCED*/
_Lock __lock_instance;
# endif
_Obj* __RESTRICT __result = *__my_free_list;
if (__result == 0)
__ret = _S_refill(_S_round_up(__n));
else {
*__my_free_list = __result -> _M_free_list_link;
__ret = __result;
}
}
return __ret;
};
参数__n是要申请内存的大小,如果大于128字节,就不受二级空间配置器管理,直接通过malloc申请,但不是简单的只做malloc,对其进行了一层封装,在malloc失败时会有异常处理,具体怎么处理后面介绍。
而如果申请的内存大小 小于128字节,就会到二级空间配置器来处理了。二级空间配置器的结构如下图:
自由链表_S_free_list的结点存放一条链表,链表的的起始地址表示一块大小为(下标+1)8的内存,要在二级空间配置器上申请一块内存,需要获取对应大小内存在自由链表的下标,_Obj* __STL_VOLATILE* __my_free_list = _S_free_list + _S_freelist_index(__n);
这句的代码就是用来定位的,需要注意是用一个二级指针接收的,如果__my_free_list为空,表示没有对应大小的内存块,这时候就需要调用_S_refill函数取填充了,具体怎么填充后面介绍。如果不为空表示有对应大小的内存块,直接把链表的第一个结点返回给用户,再更新链表头节点即可。
# ifndef _NOTHREADS
/*REFERENCED*/
_Lock __lock_instance;
# endif
在多线程环境下,因为自由链表定义在数据段,自由链表需要互斥的访问,在C++STL的设计完全没有考虑多线程,而SGI STL是线程安全的。
边栏推荐
- hicp第六天
- Alibaba Cloud Cloud Server Firewall Settings
- 【无标题】
- 40.【vector的运用】
- Judging from the Internet:
- 代币(双代币)系统研究
- The blockbuster IP that has been popular in the world for 25 years, the new work has become a script paradise
- typescript2-typescript为什么给js添加类型支持
- 蓝牙技术|了解蓝牙LE Audio的Auracast广播音频
- 谷粒商城--环境部署(2022/7/28最新)
猜你喜欢
随机推荐
C# uses RestSharp to implement Get, Post requests (2)
02 多线程与高并发 - synchronized 解析
RFID固定资产盘点系统给企业带来哪些便利?
Common configuration
Thinking about digital transformation of construction enterprises in 2022, the road to digital transformation of construction enterprises
桌面软件开发框架大赏
The blockbuster IP that has been popular in the world for 25 years, the new work has become a script paradise
JS中对事件流的理解
Lenovo Notebook How to Change Windows 10 Boot Logo Icon
MagicDraw二次开发过程
typescript7-typescript常用类型
hcip 第14天学习笔记
【WeChat Mini Program】Page Events
智能存储柜——解决您的存储需求
jdbc ResultSetMetaData获取tableName问题
C13—使用innosetup工具制作软件安装向导2022-07-23
代币(双代币)系统研究
hicp第六天
What convenience does the RFID fixed asset inventory system bring to enterprises?
SwiftUI SQLite 教程之 构建App本地数据库实现创建、读取、更新和删除(教程含完成项目源码)