初始申请内存,将内存分为内存区,各个内存区以链表相连,每个内存区中又有内存块链表
#ifndef UNTITLED5_MEMORY_POOL_H #define UNTITLED5_MEMORY_POOL_H #include<stdint.h> #include <mutex> template<size_t BlockSize,size_t BlockNum =10> class MemoryPool { public: MemoryPool() { std::lock_guard<std::mutex>lock(mtx); free_block_head=NULL; mem_chunk_head=NULL; } ~MemoryPool() { std::lock_guard<std::mutex> lk(mtx); MemChunk *p; while(mem_chunk_head)//循环链表删除内存区 { p=mem_chunk_head->next; delete mem_chunk_head; mem_chunk_head= NULL; mem_chunk_head=p; } } void *allocate()//分配空间 { std::lock_guard<std::mutex>lk(mtx); if(!free_block_head) {//首内存块为空 MemChunk *new_chunk = new MemChunk;//申请一个内存区 std::cout<< sizeof(FreeBlock)<<" "<<sizeof(MemChunk)<<std::endl; new_chunk->next = NULL; free_block_head = &(new_chunk->blocks[0]); for (int i = 1; i < BlockNum; i++) { new_chunk->blocks[i - 1].next = &(new_chunk->blocks[i]);//构建内存区中的内存块链表 } new_chunk->blocks[BlockNum - 1].next = NULL; if (!mem_chunk_head) {//首内存区为空 mem_chunk_head = new_chunk; } else {//不为空直接插入到首部内存区链表 mem_chunk_head->next = new_chunk; mem_chunk_head = new_chunk; } } void *object_block=free_block_head;//取出首内存块 free_block_head=free_block_head->next; return object_block; } void *allocate(size_t size)//申请多少字节内存 { std::lock_guard<std::mutex>lk(mtx); int n=size/BlockSize; void *p=allocate();//返回首内存块地址 for(int i=1;i<n;i++) { allocate(); } return p; } void deallocate(void *p)//回收内存 { std::lock_guard<std::mutex>lk(mtx); FreeBlock *block= static_cast<FreeBlock*>(p); block->next=free_block_head; free_block_head=block; } private: struct FreeBlock//内存块 { unsigned char data[BlockSize]; FreeBlock *next; }; FreeBlock *free_block_head; struct MemChunk//内存区 { FreeBlock blocks[BlockNum]; MemChunk *next; }; MemChunk *mem_chunk_head; //thread safe std::mutex mtx; std::mutex array_mtx; }; #endif //UNTITLED5_MEMORY_POOL_H
#include <iostream> #include "memory_pool.h" class MyObject { public: MyObject(int x):data(x) { } ~MyObject() { } int data; void *operator new(size_t size); void operator delete(void *p); void *operator new[](size_t size); void operator delete[](void *p); }; MemoryPool<sizeof(MyObject),3>gMemPook; void * MyObject::operator new(size_t size) { return gMemPook.allocate(); } void MyObject::operator delete(void *p) { gMemPook.deallocate(p); } int main() { MyObject *p1=new MyObject(1); MyObject *p2=new MyObject(2); std::cout << "p1 " << p1<<" "<<p1->data<<std::endl; std::cout << "p2 " << p2<<" "<<p2->data<<std::endl; delete p1; delete p2; return 0; }