00001
00002
00003 #ifndef VECTOR_POOL_H
00004 #define VECTOR_POOL_H
00005
00006 #ifdef HAVE_CONFIG_H
00007 #include "config.h"
00008 #endif
00009
00010 #include "misc.h"
00011 #include "multithread.h"
00012
00013 namespace FD {
00014
00015
00016 template <class T>
00017 class Vector;
00018
00019 #define MAX_SMALL 512
00020 #define MAX_BITS 32
00021
00022 template <class T>
00023 class VectorPool {
00024 protected:
00025 size_t max_stored;
00026
00027 std::vector<std::vector <Vector<T> *> > smallList;
00028 std::vector<std::vector <Vector<T> *> > largeList;
00029 FastMutex mutex;
00030
00031 public:
00032 VectorPool(int _max_stored=50)
00033 : max_stored(_max_stored)
00034 , smallList (MAX_SMALL+1)
00035 , largeList (MAX_BITS+1)
00036 {}
00037
00038 Vector<T> *newVector (int size)
00039 {
00040 mutex.lock();
00041 if (size <= MAX_SMALL)
00042 {
00043 std::vector <Vector<T> *> &stack = smallList[size];
00044 if (stack.empty())
00045 {
00046 mutex.unlock();
00047 return new Vector<T> (size);
00048 } else {
00049 Vector<T> *ret = stack.back();
00050 stack.pop_back();
00051 ret->ref();
00052 mutex.unlock();
00053 return ret;
00054 }
00055 } else {
00056 std::vector <Vector<T> *> &stack = largeList[(int)log2(size)];
00057 if (stack.empty())
00058 {
00059 mutex.unlock();
00060 return new Vector<T> (size);
00061 } else {
00062 Vector<T> *ret = stack.back();
00063 stack.pop_back();
00064 ret->ref();
00065 ret->resize(size);
00066 mutex.unlock();
00067 return ret;
00068
00069 }
00070 }
00071 }
00072 void release(Vector<T> *vec)
00073 {
00074 mutex.lock();
00075 int sz = vec->size();
00076 if (sz <= MAX_SMALL)
00077 {
00078 std::vector <Vector<T> *> &stack = smallList[sz];
00079 if (stack.size() > max_stored)
00080 {
00081 delete vec;
00082 } else {
00083 stack.push_back(vec);
00084 }
00085
00086 } else {
00087 std::vector <Vector<T> *> &stack = largeList[(int)log2(sz)];
00088 if (stack.size() > max_stored)
00089 {
00090 delete vec;
00091 } else {
00092 stack.push_back(vec);
00093 }
00094 }
00095 mutex.unlock();
00096 }
00097 };
00098
00099 }
00100 #endif