boost 对象池优化(线程安全)
内存管理中最常用的就是对象池了
boost的object_pool设计概念是好的,但是中间的排序逻辑消耗非常大,所以我都是使用pool修改来使用
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #pragma once 2 #include <boost/pool/pool.hpp> 3 #include <boost/smart_ptr.hpp> 4 #include <boost/bind.hpp> 5 #include <boost/thread.hpp> 6 #include <boost/thread/null_mutex.hpp> 7 8 //线程安全 boost::mutex 9 //非线程使用 boost::null_mutex 10 template<class obj_type, class M = boost::null_mutex> 11 class enable_obj_pool 12 { 13 static boost::pool<> m_pool; 14 static M m_lock; 15 16 public: 17 enable_obj_pool(){} 18 virtual ~enable_obj_pool(){} 19 20 typedef boost::shared_ptr<obj_type> ObjPtr; 21 22 static boost::shared_ptr<obj_type> malloc() 23 { 24 boost::lock_guard<M> gurad(m_lock); 25 void * mem = m_pool.malloc(); 26 if(!mem) 27 return nullptr; 28 29 obj_type* pobj = new(mem) obj_type(); 30 31 return boost::shared_ptr<obj_type>(pobj, boost::bind(&obj_type::free, _1));; 32 } 33 34 static void free(obj_type* pobj) 35 { 36 boost::lock_guard<M> gurad(m_lock); 37 pobj->~obj_type(); 38 m_pool.free(pobj); 39 } 40 41 //手动释放未使用的内存 42 static void release() 43 { 44 boost::lock_guard<M> gurad(m_lock); 45 m_pool.release_memory(); 46 } 47 48 static ObjPtr EmptyPtr; 49 }; 50 51 #define enable_obj_pool_init(c_type, m_type) 52 template <class c_type, class m_type>\ 53 boost::pool<> enable_obj_pool<c_type, m_type>::m_pool(sizeof(c_type));\ 54 template <class c_type, class m_type>\ 55 m_type enable_obj_pool<c_type, m_type>::m_lock;\ 56 template <class c_type, class m_type>\ 57 boost::shared_ptr<c_type> enable_obj_pool<c_type, m_type>::EmptyPtr; 58 59 60 61 #ifndef CONVERT_POINT 62 #define CONVERT_POINT(dectype, srcptr) boost::static_pointer_cast<dectype>(srcptr) 63 #endif
下面是对比测试结果:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // CPPlusTest.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include "enable_object_pool.h" 6 #include <string> 7 #include <list> 8 #include <boost/timer.hpp> 9 #include <boost/pool/object_pool.hpp> 10 11 class A : public enable_obj_pool<A> 12 { 13 public: 14 A() 15 { 16 s=""; 17 }; 18 ~A() 19 { 20 } 21 std::string s; 22 }; 23 enable_obj_pool_init(A); 24 25 boost::object_pool<A> oap; 26 27 void oap_free(A* pa) 28 { 29 oap.destroy(pa); 30 } 31 32 int _tmain(int argc, _TCHAR* argv[]) 33 { 34 const int testcount = 100000; 35 std::list<boost::shared_ptr<A>> sl; 36 boost::timer t; 37 { 38 printf("\ntest 1\n"); 39 t.restart(); 40 for (int i = 0;i<testcount;i++) 41 { 42 sl.push_back(A::malloc()); 43 } 44 printf("new time:%lf\n",t.elapsed()); 45 } 46 47 t.restart(); 48 sl.clear(); 49 printf("del time:%lf\n",t.elapsed()); 50 51 printf("\ntest 2\n"); 52 t.restart(); 53 for (int i = 0;i<testcount;i++) 54 { 55 sl.push_back(boost::shared_ptr<A>(oap.construct(), boost::bind(&oap_free, _1))); 56 } 57 printf("new time:%lf\n",t.elapsed()); 58 59 t.restart(); 60 sl.clear(); 61 printf("del time:%lf\n",t.elapsed()); 62 63 getchar(); 64 return 0; 65 }