Pool.h

Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2006-2010 Jacek Sieka, arnetheduck on gmail point com
00003  *
00004  * This program is free software; you can redistribute it and/or modify
00005  * it under the terms of the GNU General Public License as published by
00006  * the Free Software Foundation; either version 2 of the License, or
00007  * (at your option) any later version.
00008  *
00009  * This program is distributed in the hope that it will be useful,
00010  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012  * GNU General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program; if not, write to the Free Software
00016  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
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         // Remove some objects every now and then...
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_
Generated on Sat Nov 27 23:37:53 2010 for adchpp by  doxygen 1.6.3