C++ std:shared_ptr自定义allocator引入内存池
ztj100 2025-01-21 23:12 27 浏览 0 评论
当C++项目里做了大量的动态内存分配与释放,可能会导致内存碎片,使系统性能降低。当动态内存分配的开销变得不容忽视时,一种解决办法是一次从操作系统分配一块大的静态内存作为内存池进行手动管理,堆对象内存分配时从内存池中分配一块类对象大小的内存,释放时并不实际将内存归还给操作系统,而是交给自定义的内存管理模块处理。本文介绍基于std::shared_ptr自定义allocator引入内存池的方法。
尝试重写new和delete运算符
项目中大量使用std::shared_ptr且与多个模块耦合, 如果直接将 std::shared_ptr 重构为手动管理裸指针的实现,改动量太大,而且可能会带来不可预料的问题。于是尝试了重写new和delete运算符并添加了打印,发现 std::shared_ptr 的创建并不会直接调用 new和 delete, 原因在于std::shared_ptr 有自己的内存分配机制。
std::allocate_shared
于是,想到了STL的一大组件 Allocator。C++提供了 std::alloc_shared 函数,可以自定义std::shared_ptr 的内存分配方式,其定义如下:
std::allocate_shared<T>(custom_alloc, std::forward<Args>(args)...);
仅需传入自定义分配器allocator和T的构造参数列表。
实际上, std::make_shared 就是对以上函数进行了封装,使用了默认的分配器。
MemoryPool的使用
内存池直接采用了相关开源项目的定义:
可以选用
https://github.com/DevShiftTeam/AppShift-MemoryPool
或
Fast Efficient Fixed-Sized Memory Pool
MemoryPoolManager 管理内存池的类
- 分配内存池
内存池需要拥有静态生命周期,因此将内存池管理类 MemoryPoolManager 设计为全局单例模式实现,定义Alloc() 和 Free() 方法,实现了内存池与自定义分配器解耦。
- 引入自旋锁实现线程安全
由于使用的相关开源内存池不是线程安全的,因此引入了自旋锁在内存池做内存分配和释放时加锁。自旋锁采用了以下文章中的实现:
Correctly implementing a spinlock in C++
MemoryPoolManager 的完整实现如下:
class MemoryPoolManager {
public:
static MemoryPoolManager& GetInstance();
void* Alloc(size_t sz);
void Free(void* p);
~MemoryPoolManager();
private:
MemoryPoolManager();
MemoryPoolManager(const MemoryPoolManager&)=delete;
MemoryPoolManager& operator=(const MemoryPoolManager&)=delete;
MemoryPool* pool_;
SpinLock spin_lock_;
};
MemoryPoolManager& MemoryPoolManager::GetInstance() {
static MemoryPoolManager instance;
return instance;
}
MemoryPoolManager::MemoryPoolManager() {
pool_ = new MemoryPool();
}
MemoryPoolManager::~MemoryPoolManager() {
std::lock_guard<SpinLock> lock(spin_lock_);
delete pool_;
}
void* MemoryPoolManager::Alloc(size_t sz) {
std::lock_guard<SpinLock> lock(spin_lock_);
return pool_->allocate(sz);
}
void MemoryPoolManager::Free(void* p) {
std::lock_guard<SpinLock> lock(spin_lock_);
pool_->free(p);
}
自定义分配器Custom Allocator
为了使用 std::alloc_shared ,还需要实现 Custom Allocator 。其中包含了需要的函数和别名定义,相关文章可参考: Building Your Own Allocators。以下接口中许多成员在C++20中被移除。
template <typename T>
class CustomAllocator {
public:
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
CustomAllocator() = default;
~CustomAllocator() = default;
template <typename U>
CustomAllocator(const CustomAllocator<U>&) noexcept {}
T* allocate(size_t n) {
return static_cast<T*>(MemoryPoolManager::GetInstance().Alloc(n * sizeof(T)));
}
void deallocate(T* p, size_t) {
MemoryPoolManager::GetInstance().Free(p);
}
size_type max_size() const noexcept {
return std::numeric_limits<size_type>::max() / sizeof(T);
}
private:
template <typename U>
friend class CustomAllocator;
};
其中T* allocate(size_t n)方法实现内存的分配, 直接调用了MemoryPoolManager的 Alloc方法;void deallocate(T* p, size_t) 做内存的释放,直接调用了MemoryPoolManager的 Free 方法。
我们知道 new操作会分配内存并会调用类的构造函数 ,那么allocate 了需要手动调用构造函数吗?
在自定义分配器中,一般不需要手动实现 construct 和 destroy,因为标准库中的 std::allocator_traits 会处理这些工作。std::allocator_traits 默认会使用 placement new 来调用对象的构造函数,并调用对象的析构函数。
相当于在CustomAllocator 中增加以下函数:
template<typename U, typename... Args>
void construct(U* p, Args&&... args) {
::new((void*)p) U(std::forward<Args>(args)...);
}
template<typename U>
void destroy(U* p) {
p->~U();
}
使用std::allocate_shared
接下来就可以使用std::allocate_shared了 ,需传入自定义分配器allocator对象和类的构造函数参数列表。仿照 std::make_shared的实现,基于可变长参数模板做了一层函数封装:
template <typename T, typename... Args>
std::shared_ptr<T> AllocateShared(Args&&... args) {
return std::allocate_shared<T>(CustomAllocator<T>(), std::forward<Args>(args)...);
}
这样,使用AllocateShared 直接就可以返回一个std::shared_ptr<Object>对象:
std::shared_ptr<Object> = AllocateShared<Object>();
实验
对这两种方法进行了对比,使用 AppShift-MemoryPool 作为内存池,一次创建N个 std::shared_ptr<object>的耗时,其中Object的大小大约2kb左右,测试结果如下,引入内存池后有明显性能提升,引入内存池后有明显性能提升,大约快了3倍:
方法\创建数量 | 1000 | 3000 |
std::shared_ptr | 1.8ms | 4.2ms |
std::alloc_shared | 0.6ms | 1.5ms |
完整代码地址
https://github.com/qiangcraft/alloc_shared/
参考
- https://docs.oracle.com/cd/E19205-01/819-3703/15_3.htm
- https://en.cppreference.com/w/cpp/memory/allocator
相关推荐
- 使用Python编写Ping监测程序(python 测验)
-
Ping是一种常用的网络诊断工具,它可以测试两台计算机之间的连通性;如果您需要监测某个IP地址的连通情况,可以使用Python编写一个Ping监测程序;本文将介绍如何使用Python编写Ping监测程...
- 批量ping!有了这个小工具,python再也香不了一点
-
号主:老杨丨11年资深网络工程师,更多网工提升干货,请关注公众号:网络工程师俱乐部下午好,我的网工朋友。在咱们网工的日常工作中,经常需要检测多个IP地址的连通性。不知道你是否也有这样的经历:对着电脑屏...
- python之ping主机(python获取ping结果)
-
#coding=utf-8frompythonpingimportpingforiinrange(100,255):ip='192.168.1.'+...
- 网站安全提速秘籍!Nginx配置HTTPS+反向代理实战指南
-
太好了,你直接问到重点场景了:Nginx+HTTPS+反向代理,这个组合是现代Web架构中最常见的一种部署方式。咱们就从理论原理→实操配置→常见问题排查→高级玩法一层层剖开说,...
- Vue开发中使用iframe(vue 使用iframe)
-
内容:iframe全屏显示...
- Vue3项目实践-第五篇(改造登录页-Axios模拟请求数据)
-
本文将介绍以下内容:项目中的public目录和访问静态资源文件的方法使用json文件代替http模拟请求使用Axios直接访问json文件改造登录页,配合Axios进行登录请求,并...
- Vue基础四——Vue-router配置子路由
-
我们上节课初步了解Vue-router的初步知识,也学会了基本的跳转,那我们这节课学习一下子菜单的路由方式,也叫子路由。子路由的情况一般用在一个页面有他的基础模版,然后它下面的页面都隶属于这个模版,只...
- Vue3.0权限管理实现流程【实践】(vue权限管理系统教程)
-
作者:lxcan转发链接:https://segmentfault.com/a/1190000022431839一、整体思路...
- swiper在vue中正确的使用方法(vue中如何使用swiper)
-
swiper是网页中非常强大的一款轮播插件,说是轮播插件都不恰当,因为它能做的事情太多了,swiper在vue下也是能用的,需要依赖专门的vue-swiper插件,因为vue是没有操作dom的逻辑的,...
- Vue怎么实现权限管理?控制到按钮级别的权限怎么做?
-
在Vue项目中实现权限管理,尤其是控制到按钮级别的权限控制,通常包括以下几个方面:一、权限管理的层级划分...
- 【Vue3】保姆级毫无废话的进阶到实战教程 - 01
-
作为一个React、Vue双修选手,在Vue3逐渐稳定下来之后,是时候摸摸Vue3了。Vue3的变化不可谓不大,所以,本系列主要通过对Vue3中的一些BigChanges做...
- Vue3开发极简入门(13):编程式导航路由
-
前面几节文章,写的都是配置路由。但是在实际项目中,下面这种路由导航的写法才是最常用的:比如登录页面,服务端校验成功后,跳转至系统功能页面;通过浏览器输入URL直接进入系统功能页面后,读取本地存储的To...
- vue路由同页面重定向(vue路由重定向到外部url)
-
在Vue中,可以使用路由的重定向功能来实现同页面的重定向。首先,在路由配置文件(通常是`router/index.js`)中,定义一个新的路由,用于重定向到同一个页面。例如,我们可以定义一个名为`Re...
- 那个 Vue 的路由,路由是干什么用的?
-
在Vue里,路由就像“页面导航的指挥官”,专门负责管理页面(组件)的切换和显示逻辑。简单来说,它能让单页应用(SPA)像多页应用一样实现“不同URL对应不同页面”的效果,但整个过程不会刷新网页。一、路...
- Vue3项目投屏功能开发!(vue投票功能)
-
最近接了个大屏项目,产品想在不同的显示器上展示大屏项目不同的页面,做出来的效果图大概长这样...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)