C++多线程环境中进行内存分配跟踪的接口类设计(全局重载new/delete操作符)

本文主要是介绍C++多线程环境中进行内存分配跟踪的接口类设计(全局重载new/delete操作符),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

通过全局重载newdelete操作符,实现堆区空间的分配和释放的跟踪记录

// Memory.h
#if TRACK_MEMORY
#ifdef PLATFORM_WINDOWS_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(size) _VCRT_ALLOCATOR
void* __CRTDECL operator new(size_t size);_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(size) _VCRT_ALLOCATOR
void* __CRTDECL operator new[](size_t size);_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(size) _VCRT_ALLOCATOR
void* __CRTDECL operator new(size_t size, const char* desc);_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(size) _VCRT_ALLOCATOR
void* __CRTDECL operator new[](size_t size, const char* desc);_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(size) _VCRT_ALLOCATOR
void* __CRTDECL operator new(size_t size, const char* file, int line);_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(size) _VCRT_ALLOCATOR
void* __CRTDECL operator new[](size_t size, const char* file, int line);void __CRTDECL operator delete(void* memory);
void __CRTDECL operator delete(void* memory, const char* desc);
void __CRTDECL operator delete(void* memory, const char* file, int line);
void __CRTDECL operator delete[](void* memory);
void __CRTDECL operator delete[](void* memory, const char* desc);
void __CRTDECL operator delete[](void* memory, const char* file, int line);#define hnew new(__FILE__, __LINE__)	// 源文件、行号,用于跟踪进行内存分配的位置
#define hdelete delete#else#warning "Memory tracking not available on non-Windows platform"
#define hnew new
#define hdelete delete#endif#else#define hnew new
#define hdelete delete#endif
// Memory.cpp
#if TRACK_MEMORY && PLATFORM_WINDOWS// windows平台的MSVC编译器的标注和属性
_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(size) _VCRT_ALLOCATOR	
void* __CRTDECL operator new(size_t size)
{return Allocator::Allocate(size);	// 分配一块大小为 size 字节的内存。
}_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(size) _VCRT_ALLOCATOR
void* __CRTDECL operator new[](size_t size)
{return Allocator::Allocate(size);	
}_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(size) _VCRT_ALLOCATOR
void* __CRTDECL operator new(size_t size, const char* desc)
{return Allocator::Allocate(size, desc);	// 分配一块大小为 size 字节的内存,并附带一个描述字符串。
}_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(size) _VCRT_ALLOCATOR
void* __CRTDECL operator new[](size_t size, const char* desc)
{return Allocator::Allocate(size, desc);
}_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(size) _VCRT_ALLOCATOR
void* __CRTDECL operator new(size_t size, const char* file, int line)
{return Allocator::Allocate(size, file, line);	// 分配一块大小为 size 字节的内存,并记录文件名和行号。
}_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(size) _VCRT_ALLOCATOR
void* __CRTDECL operator new[](size_t size, const char* file, int line)
{return Allocator::Allocate(size, file, line);
}void __CRTDECL operator delete(void* memory)
{return Allocator::Free(memory);
}void __CRTDECL operator delete(void* memory, const char* desc)
{return Allocator::Free(memory);
}void __CRTDECL operator delete(void* memory, const char* file, int line)
{return Allocator::Free(memory);
}void __CRTDECL operator delete[](void* memory)
{return Allocator::Free(memory);
}void __CRTDECL operator delete[](void* memory, const char* desc)
{return Allocator::Free(memory);
}void __CRTDECL operator delete[](void* memory, const char* file, int line)
{return Allocator::Free(memory);
}#endif

自定义内存分配接口

// Memory.h
#pragma once#include <map>
#include <mutex>// 用于记录整个程序内存分配的情况
struct AllocationStats
{size_t TotalAllocated = 0;size_t TotalFreed = 0;
};// 用于记录单个内存分配的信息
struct Allocation
{void* Memory = 0;size_t Size = 0;const char* Category = 0;	// 描述信息,比如记录申请内存分配的代码的位置,该内存的用处等等
};// 对外接口,用于获取记录分配情况的静态对象(仅Memory.cpp可见)
namespace Memory
{const AllocationStats& GetAllocationStats();
}// Map Allocator 自定义的内存分配器,用于管理std::map的键值对的内存分配,
template <class T>
struct Mallocator
{typedef T value_type;Mallocator() = default;template <class U> constexpr Mallocator(const Mallocator <U>&) noexcept {}T* allocate(std::size_t n){
#undef max// 64位操作系统最大寻址内存值为2^64,因此要保证传入的n是小于这个的if (n > std::numeric_limits<std::size_t>::max() / sizeof(T))throw std::bad_array_new_length();if (auto p = static_cast<T*>(std::malloc(n * sizeof(T)))) {return p;}throw std::bad_alloc();}void deallocate(T* p, std::size_t n) noexcept {std::free(p);}
};struct AllocatorData
{// 2个自定义分配器,分别用于管理std::map中的 这种键值对的内存分配: // key:                   value:// const void* const  --  Allocation// const char* const  --  AllocationStatsusing MapAlloc = Mallocator<std::pair<const void* const, Allocation>>;using StatsMapAlloc = Mallocator<std::pair<const char* const, AllocationStats>>;using AllocationStatsMap = std::map<const char*, AllocationStats, std::less<const char*>, StatsMapAlloc>;// 两个std::map容器// key:内存地址;value: Allocation结构体,记录了内存的指针、大小、描述信息std::map<const void*, Allocation, std::less<const void*>, MapAlloc> m_AllocationMap;// key:描述信息;value: 内存总共分配数量、释放数量AllocationStatsMap m_AllocationStatsMap;std::mutex m_Mutex, m_StatsMutex;
};// 内存分配器接口定义
class Allocator
{
public:static void Init();static void* AllocateRaw(size_t size);static void* Allocate(size_t size);static void* Allocate(size_t size, const char* desc);static void* Allocate(size_t size, const char* file, int line);static void Free(void* memory);static const AllocatorData::AllocationStatsMap& GetAllocationStats() { return s_Data->m_AllocationStatsMap; }
private:inline static AllocatorData* s_Data = nullptr;
};
#include "Memory.h"#include <memory>
#include <map>
#include <mutex>#include "Log.h"
// 用于记录全局内存分配、释放的信息
static Hazel::AllocationStats s_GlobalStats;// 分配器是否正在进行初始化操作(应付多线程)
static bool s_InInit = false;// 初始化阶段,主要是分配一个静态的AllocatorData对象(lazy 初始化)
void Allocator::Init()
{if (s_Data)return;s_InInit = true;AllocatorData* data = (AllocatorData*)Allocator::AllocateRaw(sizeof(AllocatorData));new(data) AllocatorData();	// 定位new(placement new)在指定地址构造目标对象,并调用构造函数初始化,释放需要调用operator deletes_Data = data;s_InInit = false;
}// 利用malloc进行原始内存分配(即不会调用构造和析构),记得手动调用Allocator::free
void* Allocator::AllocateRaw(size_t size)
{return malloc(size);
}void* Allocator::Allocate(size_t size)
{// 如果一个线程正在执行Init()函数,分配请求用原始内存分配来处理if (s_InInit)return AllocateRaw(size);if (!s_Data)Init();void* memory = malloc(size);{std::scoped_lock<std::mutex> lock(s_Data->m_Mutex);Allocation& alloc = s_Data->m_AllocationMap[memory];	// 没有该key就创建,有就返回alloc.Memory = memory;alloc.Size = size;s_GlobalStats.TotalAllocated += size;}return memory;
}// 分配带有描述信息的内存,这个内存不仅要记录到总分配内存计数器中,还要把这种类型的内存单独进行计数
void* Allocator::Allocate(size_t size, const char* desc)
{if (!s_Data)Init();void* memory = malloc(size);{std::scoped_lock<std::mutex> lock(s_Data->m_Mutex);Allocation& alloc = s_Data->m_AllocationMap[memory];alloc.Memory = memory;alloc.Size = size;alloc.Category = desc;s_GlobalStats.TotalAllocated += size;if (desc)s_Data->m_AllocationStatsMap[desc].TotalAllocated += size; // 单独计数}return memory;
}
// line没用到,目前只想逐源文件记录内存分配量
void* Allocator::Allocate(size_t size, const char* file, int line)
{if (!s_Data)Init();void* memory = malloc(size);{std::scoped_lock<std::mutex> lock(s_Data->m_Mutex);Allocation& alloc = s_Data->m_AllocationMap[memory];alloc.Memory = memory;alloc.Size = size;alloc.Category = file;s_GlobalStats.TotalAllocated += size;s_Data->m_AllocationStatsMap[file].TotalAllocated += size;}return memory;
}void Allocator::Free(void* memory)
{if (memory == nullptr)return;{// map中有,计数更新并移除bool found = false;{std::scoped_lock<std::mutex> lock(s_Data->m_Mutex);auto allocMapIt = s_Data->m_AllocationMap.find(memory);found = allocMapIt != s_Data->m_AllocationMap.end();if (found)	{const Allocation& alloc = allocMapIt->second;s_GlobalStats.TotalFreed += alloc.Size;if (alloc.Category)s_Data->m_AllocationStatsMap[alloc.Category].TotalFreed += alloc.Size;s_Data->m_AllocationMap.erase(memory);}}if (!found)LOG("Memory", "Memory block {0} not present in alloc map", memory);}free(memory);
}namespace Memory {const AllocationStats& GetAllocationStats() { return s_GlobalStats; }
}

这篇关于C++多线程环境中进行内存分配跟踪的接口类设计(全局重载new/delete操作符)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/636752

相关文章

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

SQL Server跟踪自动统计信息更新实战指南

《SQLServer跟踪自动统计信息更新实战指南》本文详解SQLServer自动统计信息更新的跟踪方法,推荐使用扩展事件实时捕获更新操作及详细信息,同时结合系统视图快速检查统计信息状态,重点强调修... 目录SQL Server 如何跟踪自动统计信息更新:深入解析与实战指南 核心跟踪方法1️⃣ 利用系统目录

MySQL 内存使用率常用分析语句

《MySQL内存使用率常用分析语句》用户整理了MySQL内存占用过高的分析方法,涵盖操作系统层确认及数据库层bufferpool、内存模块差值、线程状态、performance_schema性能数据... 目录一、 OS层二、 DB层1. 全局情况2. 内存占js用详情最近连续遇到mysql内存占用过高导致

Python进行JSON和Excel文件转换处理指南

《Python进行JSON和Excel文件转换处理指南》在数据交换与系统集成中,JSON与Excel是两种极为常见的数据格式,本文将介绍如何使用Python实现将JSON转换为格式化的Excel文件,... 目录将 jsON 导入为格式化 Excel将 Excel 导出为结构化 JSON处理嵌套 JSON:

Mysql中设计数据表的过程解析

《Mysql中设计数据表的过程解析》数据库约束通过NOTNULL、UNIQUE、DEFAULT、主键和外键等规则保障数据完整性,自动校验数据,减少人工错误,提升数据一致性和业务逻辑严谨性,本文介绍My... 目录1.引言2.NOT NULL——制定某列不可以存储NULL值2.UNIQUE——保证某一列的每一

C++11范围for初始化列表auto decltype详解

《C++11范围for初始化列表autodecltype详解》C++11引入auto类型推导、decltype类型推断、统一列表初始化、范围for循环及智能指针,提升代码简洁性、类型安全与资源管理效... 目录C++11新特性1. 自动类型推导auto1.1 基本语法2. decltype3. 列表初始化3

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件

RabbitMQ消费端单线程与多线程案例讲解

《RabbitMQ消费端单线程与多线程案例讲解》文章解析RabbitMQ消费端单线程与多线程处理机制,说明concurrency控制消费者数量,max-concurrency控制最大线程数,prefe... 目录 一、基础概念详细解释:举个例子:✅ 单消费者 + 单线程消费❌ 单消费者 + 多线程消费❌ 多

C++中detach的作用、使用场景及注意事项

《C++中detach的作用、使用场景及注意事项》关于C++中的detach,它主要涉及多线程编程中的线程管理,理解detach的作用、使用场景以及注意事项,对于写出高效、安全的多线程程序至关重要,下... 目录一、什么是join()?它的作用是什么?类比一下:二、join()的作用总结三、join()怎么