Boost pool库导引

来源:互联网 发布:java web docker镜像 编辑:程序博客网 时间:2024/04/29 18:04

        作为一名C\C++程序员,我们无数次的与动态分配内存打过交道,可能我们已经习惯于使用new和delete关键字来申请与回收内存,但是在某些程序中我们可能会因为使用new和delete而惹来麻烦,我之前写过一个程序,需要频繁的申请和释放一些10KB以内的内存块,在程序运行初期程序一切正常,但是当运行了几十分钟后每次申请一块内存需要5s+的时间,并且如果所需内存稍大则会抛出bad_alloc异常,很明显,频繁的申请与释放造成了很多的内存碎片,为此,我们不得不使用内存池来解决这个麻烦。

        据我了解在Boost和ACE中都有内存池的实现,但是ACE主要涉及网络编程,而Boost适用于各个领域,各个子库之间的耦合也很小,所以我们这里选择Boost的Pool子库。

        Boost的Pool子库是一个轻量级的库,提供了4个接口:pool、object_pool、singleton_pool和pool_alloc。我们分别对它们进行学习。

        Pool是一个快速的内存分配器,并且可以保证所分配区块(chunk)以合适的方式对齐。Pool被包含在“pool.hpp”头文件里。这个接口是一个简单的对象使用接口(Object Usage interface),如果分配失败会返回Null。

 

void func(){  boost::pool<> p(sizeof(int));  for (int i = 0; i < 10000; ++i)  {    int * const t = p.malloc();    ... // Do something with t; don't take the time to free() it  }} // on function exit, p is destroyed, and all malloc()'ed ints are implicitly freed


 

        object_pool是一个分配失败时返回Null的对象使用接口,但是当分配区块时知道对象的类型,当从object_pool中释放区块时对象的析构函数会被调用。

 

Example:struct X { ... }; // has destructor with side-effectsvoid func(){  boost::object_pool<X> p;  for (int i = 0; i < 10000; ++i)  {    X * const t = p.malloc();    ... // Do something with t; don't take the time to free() it  }} // on function exit, p is destroyed, and all destructors for the X objects are called


 

        singleton_pool是一个分配失败时返回Null的单例使用接口(Singleton Usage interface),它没有公有的构造函数,因此只能使用它的静态方法来分配内存,因而也是线程安全的。

 

struct MyPoolTag { };typedef boost::singleton_pool<MyPoolTag, sizeof(int)> my_pool;void func(){  for (int i = 0; i < 10000; ++i)  {    int * const t = my_pool::malloc();    ... // Do something with t; don't take the time to free() it  }  // Explicitly free all malloc()'ed int's  my_pool::purge_memory();}

        pool_alloc是一个分配失败时抛出异常的单例使用接口,是在singleton_pool接口之上构建的,并且提供了与标准分配器兼容的类。

 

void func(){  std::vector<int, boost::pool_allocator<int> > v;  for (int i = 0; i < 10000; ++i)    v.push_back(13);} // Exiting the function does NOT free the system memory allocated by the pool allocator  // You must call  //  boost::singleton_pool<boost::pool_allocator_tag, sizeof(int)>::release_memory()  // in order to force that


 

原创粉丝点击