c语言内存池的实现原理,c语言内存布局

一、为什么需要使用内存池

在C/C++中我们通常使用malloc,free或new,delete来动态分配内存。

一方面,因为这些函数涉及到了系统调用,所以频繁的调用必然会导致程序性能的损耗;

另一方面,频繁的分配和释放小块内存会导致大量的内存碎片的产生,当碎片积累到一定的量之后,将无法分配到连续的内存空间,系统不得不进行碎片整理来满足分配到连续的空间,这样不仅会导致系统性能损耗,而且会导致程序对内存的利用率低下。

当然,如果我们的程序不需要频繁的分配和释放小块内存,那就没有使用内存池的必要,直接使用malloc,free或new,delete函数即可。

二、内存池的实现方案

内存池的实现原理大致如下:

提前申请一块大内存由内存池自己管理,并分成小片供给程序使用。程序使用完之后将内存归还到内存池中(并没有真正的从系统释放),当程序再次从内存池中请求内存时,内存池将池子中的可用内存片返回给程序使用。

我们在设计内存池的实现方案时,需要考虑到以下问题:

内存池是否可以自动增长?

如果内存池的最大空间是固定的(也就是非自动增长),那么当内存池中的内存被请求完之后,程序就无法再次从内存池请求到内存。所以需要根据程序对内存的实际使用情况来确定是否需要自动增长。

内存池的总内存占用是否只增不减?

如果内存池是自动增长的,就涉及到了“内存池的总内存占用是否是只增不减”这个问题了。试想,程序从一个自动增长的内存池中请求了1000个大小为100KB的内存片,并在使用完之后全部归还给了内存池,而且假设程序之后的逻辑最多之后请求10个100KB的内存片,那么该内存池中的900个100KB的内存片就一直处于闲置状态,程序的内存占用就一直不会降下来。对内存占用大小有要求的程序需要考虑到这一点。

内存池中内存片的大小是否固定?

如果每次从内存池中的请求的内存片的大小如果不固定,那么内存池中的每个可用内存片的大小就不一致,程序再次请求内存片的时候,内存池就需要在“匹配最佳大小的内存片”和“匹配操作时间”上作出衡量。“最佳大小的内存片”虽然可以减少内存的浪费,但可能会导致“匹配时间”变长。

内存池是否是线程安全的?

是否允许在多个线程中同时从同一个内存池中请求和归还内存片?这个线程安全可以由内存池来实现,也可以由使用者来保证。

内存片分配出去之前和归还到内存池之后,其中的内容是否需要被清除?

程序可能出现将内存片归还给内存池之后,仍然使用内存片的地址指针进行内存读写操作,这样就会导致不可预期的结果。将内容清零只能尽量的(也不一定能)将问题抛出来,但并不能解决任何问题,而且将内容清零会消耗一定的CPU时间。所以,最终最好还是需要由内存池的使用者来保证这种安全性。

是否兼容std::allocator?

STL标准库中的大多类都支持用户提供一个自定义的内存分配器,默认使用的是std::allocator,如std::string:

typedef basic_string<char, char_traits<char>, allocator<char> > string;

如果我们的内存池兼容std::allocator,那么我们就可以使用我们自己的内存池来替换默认的std::allocator分配器,如:

typedef basic_string<char, char_traits<char>, MemoryPoll<char> > mystring;

更多Linux内核视频教程资料文档私信【内核大礼包】自行获取。

 

三、内存池的具体实现

计划实现一个内存池管理的类MemoryPool,它具有如下特性:

  1. 内存池的总大小自动增长。
  2. 内存池中内存片的大小固定。
  3. 支持线程安全。
  4. 在内存片被归还之后,清除其中的内容。
  5. 兼容std::allocator。

因为内存池的内存片的大小是固定的,不涉及到需要匹配最合适大小的内存片,由于会频繁的进行插入、移除的操作,但查找比较少,故选用链表数据结构来管理内存池中的内存片。

MemoryPool中有2个链表,它们都是双向链表(设计成双向链表主要是为了在移除指定元素时,能够快速定位该元素的前后元素,从而在该元素被移除后,将其前后元素连接起来,保证链表的完整性):

  1. data_element_ 记录以及分配出去的内存片。
  2. free_element_ 记录未被分配出去的内存片。

MemoryPool实现代码

代码中使用了std::mutex等C++11才支持的特性,所以需要编译器最低支持C++11:

#ifndef PPX_BASE_MEMORY_POOL_H_

#define PPX_BASE_MEMORY_POOL_H_



#include <climits>

#include <cstddef>

#include <mutex>



namespace ppx {

    namespace base {

        template <typename T, size_t BlockSize = 4096, bool ZeroOnDeallocate = true>

        class MemoryPool {

        public:

            /* Member types */

            typedef T               value_type;

            typedef T*              pointer;

            typedef T&              reference;

            typedef const T*        const_pointer;

            typedef const T&        const_reference;

            typedef size_t          size_type;

            typedef ptrdiff_t       difference_type;

            typedef std::false_type propagate_on_container_copy_assignment;

            typedef std::true_type  propagate_on_container_move_assignment;

            typedef std::true_type  propagate_on_container_swap;



            template <typename U> struct rebind {

                typedef MemoryPool<U> other;

            };



            /* Member functions */

            MemoryPool() noexcept;

            MemoryPool(const MemoryPool& memoryPool) noexcept;

            MemoryPool(MemoryPool&& memoryPool) noexcept;

            template <class U> MemoryPool(const MemoryPool<U>& memoryPool) noexcept;



            ~MemoryPool() noexcept;



            MemoryPool& operator=(const MemoryPool& memoryPool) = delete;

            MemoryPool& operator=(MemoryPool&& memoryPool) noexcept;



            pointer address(reference x) const noexcept;

            const_pointer address(const_reference x) const noexcept;



            // Can only allocate one object at a time. n and hint are ignored

            pointer allocate(size_type n = 1, const_pointer hint = 0);

            void deallocate(pointer p, size_type n = 1);



            size_type max_size() const noexcept;



            template <class U, class... Args> void construct(U* p, Args&&... args);

            template <class U> void destroy(U* p);



            template <class... Args> pointer newElement(Args&&... args);

            void deleteElement(pointer p);



        private:

            struct Element_ {

                Element_* pre;

                Element_* next;

            };



            typedef char* data_pointer;

            typedef Element_ element_type;

            typedef Element_* element_pointer;



            element_pointer data_element_;

            element_pointer free_element_;



            std::recursive_mutex m_;



            size_type padPointer(data_pointer p, size_type align) const noexcept;

            void allocateBlock();



            static_assert(BlockSize >= 2 * sizeof(element_type), "BlockSize too small.");

        };





        template <typename T, size_t BlockSize,  bool ZeroOnDeallocate>

        inline typename MemoryPool<T, BlockSize, ZeroOnDeallocate>::size_type

            MemoryPool<T, BlockSize, ZeroOnDeallocate>::padPointer(data_pointer p, size_type align)

            const noexcept {

            uintptr_t result = reinterpret_cast<uintptr_t>(p);

            return ((align - result) % align);

        }







        template <typename T, size_t BlockSize,  bool ZeroOnDeallocate>

        MemoryPool<T, BlockSize, ZeroOnDeallocate>::MemoryPool()

            noexcept {

            data_element_ = nullptr;

            free_element_ = nullptr;

        }



        template <typename T, size_t BlockSize,  bool ZeroOnDeallocate>

        MemoryPool<T, BlockSize, ZeroOnDeallocate>::MemoryPool(const MemoryPool& memoryPool)

            noexcept :

            MemoryPool() {

        }



        template <typename T, size_t BlockSize,  bool ZeroOnDeallocate>

        MemoryPool<T, BlockSize, ZeroOnDeallocate>::MemoryPool(MemoryPool&& memoryPool)

            noexcept {

            std::lock_guard<std::recursive_mutex> lock(m_);



            data_element_ = memoryPool.data_element_;

            memoryPool.data_element_ = nullptr;

            free_element_ = memoryPool.free_element_;

            memoryPool.free_element_ = nullptr;

        }



        template <typename T, size_t BlockSize,  bool ZeroOnDeallocate>

        template<class U>

        MemoryPool<T, BlockSize, ZeroOnDeallocate>::MemoryPool(const MemoryPool<U>& memoryPool)

            noexcept :

            MemoryPool() {

        }



        template <typename T, size_t BlockSize,  bool ZeroOnDeallocate>

        MemoryPool<T, BlockSize, ZeroOnDeallocate>&

            MemoryPool<T, BlockSize, ZeroOnDeallocate>::operator=(MemoryPool&& memoryPool)

            noexcept {

            std::lock_guard<std::recursive_mutex> lock(m_);



            if (this != &memoryPool) {

                std::swap(data_element_, memoryPool.data_element_);

                std::swap(free_element_, memoryPool.free_element_);

            }

            return *this;

        }



        template <typename T, size_t BlockSize,  bool ZeroOnDeallocate>

        MemoryPool<T, BlockSize, ZeroOnDeallocate>::~MemoryPool()

            noexcept {

            std::lock_guard<std::recursive_mutex> lock(m_);



            element_pointer curr = data_element_;

            while (curr != nullptr) {

                element_pointer prev = curr->next;

                operator delete(reinterpret_cast<void*>(curr));

                curr = prev;

            }



            curr = free_element_;

            while (curr != nullptr) {

                element_pointer prev = curr->next;

                operator delete(reinterpret_cast<void*>(curr));

                curr = prev;

            }

        }



        template <typename T, size_t BlockSize,  bool ZeroOnDeallocate>

        inline typename MemoryPool<T, BlockSize, ZeroOnDeallocate>::pointer

            MemoryPool<T, BlockSize, ZeroOnDeallocate>::address(reference x)

            const noexcept {

            return &x;

        }



        template <typename T, size_t BlockSize,  bool ZeroOnDeallocate>

        inline typename MemoryPool<T, BlockSize, ZeroOnDeallocate>::const_pointer

            MemoryPool<T, BlockSize, ZeroOnDeallocate>::address(const_reference x)

            const noexcept {

            return &x;

        }



        template <typename T, size_t BlockSize,  bool ZeroOnDeallocate>

        void

            MemoryPool<T, BlockSize, ZeroOnDeallocate>::allocateBlock() {

            // Allocate space for the new block and store a pointer to the previous one

            data_pointer new_block = reinterpret_cast<data_pointer> (operator new(BlockSize));

            element_pointer new_ele_pointer = reinterpret_cast<element_pointer>(new_block);

            new_ele_pointer->pre = nullptr;

            new_ele_pointer->next = nullptr;



            if (data_element_) {

                data_element_->pre = new_ele_pointer;

            }



            new_ele_pointer->next = data_element_;

            data_element_ = new_ele_pointer;

        }



        template <typename T, size_t BlockSize,  bool ZeroOnDeallocate>

        inline typename MemoryPool<T, BlockSize, ZeroOnDeallocate>::pointer

            MemoryPool<T, BlockSize, ZeroOnDeallocate>::allocate(size_type n, const_pointer hint) {

            std::lock_guard<std::recursive_mutex> lock(m_);



            if (free_element_ != nullptr) {

                data_pointer body =

                    reinterpret_cast<data_pointer>(reinterpret_cast<data_pointer>(free_element_) + sizeof(element_type));



                size_type bodyPadding = padPointer(body, alignof(element_type));



                pointer result = reinterpret_cast<pointer>(reinterpret_cast<data_pointer>(body + bodyPadding));



                element_pointer tmp = free_element_;



                free_element_ = free_element_->next;



                if (free_element_)

                    free_element_->pre = nullptr;



                tmp->next = data_element_;

                if (data_element_)

                    data_element_->pre = tmp;

                tmp->pre = nullptr;

                data_element_ = tmp;



                return result;

            }

            else {

                allocateBlock();



                data_pointer body =

                    reinterpret_cast<data_pointer>(reinterpret_cast<data_pointer>(data_element_) + sizeof(element_type));



                size_type bodyPadding = padPointer(body, alignof(element_type));



                pointer result = reinterpret_cast<pointer>(reinterpret_cast<data_pointer>(body + bodyPadding));



                return result;

            }

        }



        template <typename T, size_t BlockSize, bool ZeroOnDeallocate>

        inline void

            MemoryPool<T, BlockSize, ZeroOnDeallocate>::deallocate(pointer p, size_type n) {

            std::lock_guard<std::recursive_mutex> lock(m_);



            if (p != nullptr) {

                element_pointer ele_p =

                    reinterpret_cast<element_pointer>(reinterpret_cast<data_pointer>(p) - sizeof(element_type));



                if (ZeroOnDeallocate) {

                    memset(reinterpret_cast<data_pointer>(p), 0, BlockSize - sizeof(element_type));

                }



                if (ele_p->pre) {

                    ele_p->pre->next = ele_p->next;

                }



                if (ele_p->next) {

                    ele_p->next->pre = ele_p->pre;

                }



                if (ele_p->pre == nullptr) {

                    data_element_ = ele_p->next;

                }



                ele_p->pre = nullptr;

                if (free_element_) {

                    ele_p->next = free_element_;

                    free_element_->pre = ele_p;

                }

                else {

                    ele_p->next = nullptr;

                }

                free_element_ = ele_p;

            }

        }



        template <typename T, size_t BlockSize, bool ZeroOnDeallocate>

        inline typename MemoryPool<T, BlockSize, ZeroOnDeallocate>::size_type

            MemoryPool<T, BlockSize, ZeroOnDeallocate>::max_size()

            const noexcept {

            size_type maxBlocks = -1 / BlockSize;

            return (BlockSize - sizeof(data_pointer)) / sizeof(element_type) * maxBlocks;

        }



        template <typename T, size_t BlockSize, bool ZeroOnDeallocate>

        template <class U, class... Args>

        inline void

            MemoryPool<T, BlockSize, ZeroOnDeallocate>::construct(U* p, Args&&... args) {

            new (p) U(std::forward<Args>(args)...);

        }



        template <typename T, size_t BlockSize, bool ZeroOnDeallocate>

        template <class U>

        inline void

            MemoryPool<T, BlockSize, ZeroOnDeallocate>::destroy(U* p) {

            p->~U();

        }



        template <typename T, size_t BlockSize, bool ZeroOnDeallocate>

        template <class... Args>

        inline typename MemoryPool<T, BlockSize, ZeroOnDeallocate>::pointer

            MemoryPool<T, BlockSize, ZeroOnDeallocate>::newElement(Args&&... args) {

            std::lock_guard<std::recursive_mutex> lock(m_);

            pointer result = allocate();

            construct<value_type>(result, std::forward<Args>(args)...);

            return result;

        }



        template <typename T, size_t BlockSize, bool ZeroOnDeallocate>

        inline void

            MemoryPool<T, BlockSize, ZeroOnDeallocate>::deleteElement(pointer p) {

            std::lock_guard<std::recursive_mutex> lock(m_);

            if (p != nullptr) {

                p->~value_type();

                deallocate(p);

            }

        }

    }

}



#endif // PPX_BASE_MEMORY_POOL_H_



使用示例:

#include <iostream>

#include <thread>

using namespace std;







class Apple {

public:

    Apple() {

        id_ = 0;

        cout << "Apple()" << endl;

    }



    Apple(int id) {

        id_ = id;

        cout << "Apple(" << id_ << ")" << endl;

    }



    ~Apple() {

        cout << "~Apple()" << endl;

    }



    void SetId(int id) {

        id_ = id;

    }



    int GetId() {

        return id_;

    }

private:

    int id_;

};







void ThreadProc(ppx::base::MemoryPool<char> *mp) {

    int i = 0;

    while (i++ < 100000) {

        char* p0 = (char*)mp->allocate();



        char* p1 = (char*)mp->allocate();



        mp->deallocate(p0);



        char* p2 = (char*)mp->allocate();



        mp->deallocate(p1);

        

        mp->deallocate(p2);



    }

}



int main()

{

    ppx::base::MemoryPool<char> mp;

    int i = 0;

    while (i++ < 100000) {

        char* p0 = (char*)mp.allocate();



        char* p1 = (char*)mp.allocate();



        mp.deallocate(p0);



        char* p2 = (char*)mp.allocate();



        mp.deallocate(p1);



        mp.deallocate(p2);



    }



    std::thread th0(ThreadProc, &mp);

    std::thread th1(ThreadProc, &mp);

    std::thread th2(ThreadProc, &mp);



    th0.join();

    th1.join();

    th2.join();



    Apple *apple = nullptr;

    {

        ppx::base::MemoryPool<Apple> mp2;

        apple = mp2.newElement(10);

        int a = apple->GetId();

        apple->SetId(10);

        a = apple->GetId();



        mp2.deleteElement(apple);

    }



    apple->SetId(12);

    int b = -4 % 4;



    int *a = nullptr;

    {

        ppx::base::MemoryPool<int, 18> mp3;

        a =  mp3.allocate();

        *a = 100;

        //mp3.deallocate(a);



        int *b =  mp3.allocate();

        *b = 200;

        //mp3.deallocate(b);



        mp3.deallocate(a);

        mp3.deallocate(b);



        int *c = mp3.allocate();

        *c = 300;

    }



    getchar();

    return 0;

}



本文来自投稿,不代表展天博客立场,如若转载,请注明出处:https://www.me900.com/326675.html

(0)

相关推荐

  • 车载中控台软件安装教程,中控怎么加装软件

    X95原生车机内容中规中矩,没啥可玩儿的。但是面对这么大的屏幕,不利用真是有点儿不甘心,其实X95的12个喇叭我在听音乐时候没有觉的很好,这个音响系统放个迪曲儿都燥不起来,有点儿闷,调了也不行。但事实证明,这个音响看电影,看电视剧挺好,有点儿剧场环绕效果。 还是先看效果:       条件准备: 1、手机A,安装悟空遥控器。 2…

    2023-06-30
  • 疯狂猜成语尸肉是什么成语(尸字下面一个肉字念什么)

    疯狂猜成语是一款根据图片猜成语的小游戏,玩家在游戏的同时还可以学习成语知识,收到很多玩家的喜爱。有一关的图片是尸肉两个字,这是什么成语呢? 答案是:行尸走肉。 【解释】:行尸:可以走动的尸体;走肉:会走动而没有灵魂的躯壳。比喻不动脑筋,不起作用,糊里糊涂过日子的人。 【出自】:晋·王嘉《拾遗记》卷六:“夫人好学,虽死若存;不学者,虽存,谓之行尸走肉耳。” 【…

    投稿 2022-01-14
  • 勇者斗恶龙怪兽仙境攻略(GBC勇者斗恶龙怪兽仙境攻略)

    暌违了多年之后,曾经依靠精美的画面制作,利用2.5D场景去隐藏谜题,并将战法贼三大职业体系融会贯通与游戏体验的《三位一体》系列回来了。在一改第三代作品首尝全3D场景制作失败后的阴霾后,全新的《三位一体4:梦魇王子》会用怎样的设计思路和独特的玩法体验来回馈期盼多年的玩家们呢? 人在画中游 《三位一体》最令人啧啧称奇的,就是在看似简单的2.5D场景内,融入了诸多…

    2023-05-25 投稿
  • 怎么看计算机ip和mac,如何查看计算机的ip地址和mac地址

    大家好,我是“科技跑的快”,今天教大家如何查看计算机IP地址以及MAC地址。 计算机的IP地址一旦被分配,可以说是固定不变的,因此,查询出计算机的IP地址,在一定程度上就实现了黑客入侵的前提工作。使用ipconfig命令可以获取本地计算机的IP地址和物理地址,想玩电脑专业或更深入的都要会这个知识。 具体的操作步骤如下。 Step 01右击【开始】按钮,在弹出…

    2023-07-10 投稿
  • 日本t恤品牌(bp公司的创始人)

        说到日本牛仔裤不得不提Pure Blue Japan(正蓝屋)。虽然PBJ不是著名的大阪五虎其中之一,但它对牛仔裤、粗斜纹棉布,尤其是靛蓝染色有着同样的执着。 日本的原牛品牌基本都有自己很鲜明的风格,而PBJ的特色在于颗粒感十足的竹节牛仔布和出色的indigo蓝染工艺。     PBJ的创始人叫岩谷建一,在他很…

    2023-05-29 投稿
  • rs232是什么接口,usb转rs232串口线设置

    在工业控制、测量、通讯等应用领域中,RS232串口作为很多重要设备标配的通信接口,发挥着至关重要的作用。 与此同时,作为电脑与串口设备之间的数据传输纽带,USB转RS232串口线也一直倍受工程师们重用! 这里小优先带大家认识一下关于串口的定义,具体说明仔细看下图↓↓↓ 由于现在主流笔记本机型搭载的主板取消了RS232接口,如果需要连接RS232串口设备进行调…

    2023-07-10 投稿
  • 青霉素在养殖上的作用,农用青霉素的作用和用途

    青霉素:我想每个人对它都还不陌生,它是我们生活中的常用药之一,其实在养殖过程中,它的作用也十分的巨大,用途十分广泛,你知道多少呢? 我们先来简单的了解一下青霉素: 一般养殖上使用的都是饮水的青钾,便宜,药效同青钠。呈白色结晶粉末状,溶于水,且不能和酸性和碱性物质同用,容易失效。水溶液不稳定,易失效,使用时的水温不能超过15度,否则会较快分解,所以使用的时候现…

    2023-07-04
  • 青岛火车站在哪个区,青岛火车站在市南还是市北

    这里是刘小顺的旅行和生活研究所。 青岛是我国山东省经济最发达的第一大城市,同时也是一座著名的海滨旅游城市,青岛因其独特的海滨风光以及中西合璧的人文特色而吸引着大量游客来到青岛旅游。 如果你来过山东青岛旅游的话,除了大家都非常熟悉的著名旅游景点之外,还有一个地方肯定会给你留下非常深刻的印象,那就是青岛火车站。 青岛火车站位于山东省青岛市市南区的泰安路,这里是青…

    2022-04-29 投稿
  • 广告投放渠道都有哪些

    总有些广告主特别心急,一上来就说要安排什么时候给投放广告;也有些广告主在准备投放广告是难免会面对媒介选择、投放周期、投放地点等问题一头雾水。要知道,在广告投放的过程中需要讲究策略、方法及技巧,才可以实现广告高效投放的效果。 无论选择哪类媒介都有一个发布流程,清楚流程减少耗费时间,贴心为大家整理一份选择卓颖户外广告投放流程攻略,希望对大家有所帮助。 第一步:了…

    2022-06-01 投稿
  • 淘宝1212活动,2020淘宝1212活动主题

    《淘宝1212活动:一场电商狂欢的深度剖析》 一、活动背景与起源 淘宝1212活动也许是淘宝平台为了在年末之际给消费者带来更多购物优惠和乐趣而推出的。 它就像是电商领域的一场年末盛宴,仿佛是在寒冷的冬天为人们送去了温暖的购物体验。 也许最初它的想法是在12月这个购物旺季,通过一系列的促销活动,吸引更多的消费者关注和参与,从而提升平台的销售额和用户活跃度。 在…

    投稿 2025-06-14
  • 双眼皮贴怎么剪,肿眼泡双眼皮贴正确贴法

    有没有和我一样一个怕疼,有没钱的又爱美的有是个不单不双还要是鱼泡丹凤眼的女孩。 我如果没睡好,眼睛马上小2倍,而且还特别凶的感觉,别人第一眼觉得我很高冷,丹凤眼的你们懂的。。。 丹凤眼的我 我可以说的上阅贴无数,胶水、双面的、线的、什么定型的等等。。我都忘了我用过多少了。那我就挑几个介绍一下(不要看我眉毛,我故意的,因为等它长,之前修残了)。 双面的: 我第…

    2023-07-04 投稿
  • cpa交友联盟(cpa交友联盟平台)

    网赚四大块,之前写了薅羊毛,今天整理一下CPA,同样以问答的方式写出来,尽量简单、通俗,让每一位新手能看懂,依旧欢迎大家一起交流。 问:什么是CPA? 答:冷门哥就不扯什么标准概念了,通俗说,CPA是一种广告的方式,即有的公司为了推广自己的产品(通常是软件、程序),按次数来支付佣金给帮忙推广的人。你只要到CPA广告联盟网站去注册,就能领取相应的广告条码和安装…

    2022-01-21 投稿