百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分析 > 正文

C++ std:shared_ptr自定义allocator引入内存池

liebian365 2024-10-31 15:16 12 浏览 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 管理内存池的类

  1. 分配内存池

内存池需要拥有静态生命周期,因此将内存池管理类 MemoryPoolManager 设计为全局单例模式实现,定义Alloc() 和 Free() 方法,实现了内存池与自定义分配器解耦。

  1. 引入自旋锁实现线程安全

由于使用的相关开源内存池不是线程安全的,因此引入了自旋锁在内存池做内存分配和释放时加锁。自旋锁采用了以下文章中的实现:

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/

参考

  1. https://docs.oracle.com/cd/E19205-01/819-3703/15_3.htm
  2. https://en.cppreference.com/w/cpp/memory/allocator

相关推荐

4万多吨豪华游轮遇险 竟是因为这个原因……

(观察者网讯)4.7万吨豪华游轮搁浅,竟是因为油量太低?据观察者网此前报道,挪威游轮“维京天空”号上周六(23日)在挪威近海发生引擎故障搁浅。船上载有1300多人,其中28人受伤住院。经过数天的调...

“菜鸟黑客”必用兵器之“渗透测试篇二”

"菜鸟黑客"必用兵器之"渗透测试篇二"上篇文章主要针对伙伴们对"渗透测试"应该如何学习?"渗透测试"的基本流程?本篇文章继续上次的分享,接着介绍一下黑客们常用的渗透测试工具有哪些?以及用实验环境让大家...

科幻春晚丨《震动羽翼说“Hello”》两万年星间飞行,探测器对地球的最终告白

作者|藤井太洋译者|祝力新【编者按】2021年科幻春晚的最后一篇小说,来自大家喜爱的日本科幻作家藤井太洋。小说将视角放在一颗太空探测器上,延续了他一贯的浪漫风格。...

麦子陪你做作业(二):KEGG通路数据库的正确打开姿势

作者:麦子KEGG是通路数据库中最庞大的,涵盖基因组网络信息,主要注释基因的功能和调控关系。当我们选到了合适的候选分子,单变量研究也已做完,接着研究机制的时便可使用到它。你需要了解你的分子目前已有哪些...

知存科技王绍迪:突破存储墙瓶颈,详解存算一体架构优势

智东西(公众号:zhidxcom)编辑|韦世玮智东西6月5日消息,近日,在落幕不久的GTIC2021嵌入式AI创新峰会上,知存科技CEO王绍迪博士以《存算一体AI芯片:AIoT设备的算力新选择》...

每日新闻播报(September 14)_每日新闻播报英文

AnOscarstatuestandscoveredwithplasticduringpreparationsleadinguptothe87thAcademyAward...

香港新巴城巴开放实时到站数据 供科技界研发使用

中新网3月22日电据香港《明报》报道,香港特区政府致力推动智慧城市,鼓励公私营机构开放数据,以便科技界研发使用。香港运输署21日与新巴及城巴(两巴)公司签署谅解备忘录,两巴将于2019年第3季度,开...

5款不容错过的APP: Red Bull Alert,Flipagram,WifiMapper

本周有不少非常出色的app推出,鸵鸟电台做了一个小合集。亮相本周榜单的有WifiMapper's安卓版的app,其中包含了RedBull的一款新型闹钟,还有一款可爱的怪物主题益智游戏。一起来看看我...

Qt动画效果展示_qt显示图片

今天在这篇博文中,主要实践Qt动画,做一个实例来讲解Qt动画使用,其界面如下图所示(由于没有录制为gif动画图片,所以请各位下载查看效果):该程序使用应用程序单窗口,主窗口继承于QMainWindow...

如何从0到1设计实现一门自己的脚本语言

作者:dong...

三年级语文上册 仿写句子 需要的直接下载打印吧

描写秋天的好句好段1.秋天来了,山野变成了美丽的图画。苹果露出红红的脸庞,梨树挂起金黄的灯笼,高粱举起了燃烧的火把。大雁在天空一会儿写“人”字,一会儿写“一”字。2.花园里,菊花争奇斗艳,红的似火,粉...

C++|那些一看就很简洁、优雅、经典的小代码段

目录0等概率随机洗牌:1大小写转换2字符串复制...

二年级上册语文必考句子仿写,家长打印,孩子照着练

二年级上册语文必考句子仿写,家长打印,孩子照着练。具体如下:...

一年级语文上 句子专项练习(可打印)

...

亲自上阵!C++ 大佬深度“剧透”:C++26 将如何在代码生成上对抗 Rust?

...

取消回复欢迎 发表评论: