Pool.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 #ifndef ADCHPP_POOL_H
00020 #define ADCHPP_POOL_H
00021
00022 #include "Mutex.h"
00023
00024 namespace adchpp {
00025
00026 template<class T>
00027 struct PoolDummy {
00028 void operator()(T&) { }
00029 };
00030
00031 template<typename T, class Clear = PoolDummy<T> >
00032 class SimplePool {
00033 public:
00034 SimplePool() : busy(0) { }
00035 ~SimplePool() { dcdebug("Busy pool objects: %d\n", (int)busy); }
00036
00037 T* get() {
00038 busy++;
00039 if(!free.empty()) {
00040 T* tmp = free.back();
00041 free.pop_back();
00042 return tmp;
00043 } else {
00044 return new T;
00045 }
00046 }
00047 void put(T* item) {
00048 dcassert(busy > 0);
00049 busy--;
00050 Clear()(*item);
00051
00052 if(free.size() > (2*busy) && free.size() > 32) {
00053 dcdebug("Clearing pool\n");
00054 while(free.size() > busy / 2) {
00055 delete free.back();
00056 free.pop_back();
00057 }
00058 }
00059 free.push_back(item);
00060 }
00061
00062 private:
00063 size_t busy;
00064 std::vector<T*> free;
00065 };
00066
00067
00069 template<class T, class Clear = PoolDummy<T> >
00070 class Pool {
00071 public:
00072 Pool() { }
00073 ~Pool() { }
00074
00075 T* get() {
00076 FastMutex::Lock l(mtx);
00077 return pool.get();
00078 }
00079 void put(T* obj) {
00080 FastMutex::Lock l(mtx);
00081 pool.put(obj);
00082 }
00083
00084 private:
00085 Pool(const Pool&);
00086 Pool& operator=(const Pool&);
00087 FastMutex mtx;
00088
00089 SimplePool<T, Clear> pool;
00090 };
00091
00092 }
00093
00094 #endif //POOL_H_