boost对象池优化(线程安全)内存管理中最常⽤的就是对象池了
boost的object_pool设计概念是好的,但是中间的排序逻辑消耗⾮常⼤,所以我都是使⽤pool修改来使⽤
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>
11class enable_obj_pool
12 {
13static boost::pool<> m_pool;
14static M m_lock;
15
16public:
17 enable_obj_pool(){}
18virtual ~enable_obj_pool(){}
19
20 typedef boost::shared_ptr<obj_type> ObjPtr;
21
22static boost::shared_ptr<obj_type> malloc()
23 {
24 boost::lock_guard<M> gurad(m_lock);
25void * mem = m_pool.malloc();
26if(!mem)
27return nullptr;
28
29 obj_type* pobj = new(mem) obj_type();
30
31return boost::shared_ptr<obj_type>(pobj, boost::bind(&obj_type::free, _1));;
32 }
33
34static 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//⼿动释放未使⽤的内存
42static void release()
43 {
44 boost::lock_guard<M> gurad(m_lock);
45 lease_memory();
46 }
47
48static 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
enable_object_pool.h
下⾯是对⽐测试结果:
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
11class A : public enable_obj_pool<A>
12 {
13public:
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
27void oap_free(A* pa)
28 {
29 oap.destroy(pa);
30 }
31
32int _tmain(int argc, _TCHAR* argv[])
33 {
34const int testcount = 100000;
35 std::list<boost::shared_ptr<A>> sl;
36 boost::timer t;
37 {
38 printf("\ntest 1\n");
39 t.restart();
40for (int i = 0;i<testcount;i++)
41 {
42 sl.push_back(A::malloc());
block truncated43 }
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();
53for (int i = 0;i<testcount;i++)
54 {
55 sl.push_back(boost::shared_ptr<A>(struct(), 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();
64return0;
65 }
CPPlusTest.cpp
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论