Go to the documentation of this file.00001 #ifndef MEGATREE_ALLOCATOR_H
00002 #define MEGATREE_ALLOCATOR_H
00003
00004 #include <vector>
00005 #include <boost/shared_ptr.hpp>
00006 #include <boost/thread/mutex.hpp>
00007 #include <cstdio>
00008
00009 namespace megatree
00010 {
00011
00012
00013 template <class T>
00014 class Allocator
00015 {
00016 public:
00017 Allocator(unsigned size=0)
00018 : objects(NULL), overflow(0)
00019 {
00020 objects = new T[size];
00021 obj_stack.reserve(size);
00022 assert(objects);
00023 for (unsigned i=0; i<size; i++)
00024 obj_stack.push_back(&objects[i]);
00025
00026 printf("Allocator for %d objects takes %d bytes\n", (int)size, (int)(size*sizeof(T)));
00027 }
00028
00029 ~Allocator()
00030 {
00031 boost::mutex::scoped_lock lock(mutex);
00032 delete [] objects;
00033 }
00034
00035 T* allocate()
00036 {
00037 boost::mutex::scoped_lock lock(mutex);
00038 assert(!obj_stack.empty());
00039 T* obj = obj_stack.back();
00040 obj_stack.pop_back();
00041 return obj;
00042 }
00043
00044 void allocateMany(size_t howmany, std::vector<T*> &vec)
00045 {
00046 boost::mutex::scoped_lock lock(mutex);
00047 assert(obj_stack.size() >= howmany);
00048
00049 typename std::vector<T*>::iterator begin = obj_stack.end() - howmany;
00050
00051
00052 vec.clear();
00053 vec.reserve(howmany);
00054 vec.insert(vec.begin(), begin, obj_stack.end());
00055 obj_stack.erase(begin, obj_stack.end());
00056 }
00057
00058
00059 void deAllocate(T* obj)
00060 {
00061 boost::mutex::scoped_lock lock(mutex);
00062 obj_stack.push_back(obj);
00063 }
00064
00065 void deallocateMany(std::vector<T*> &vec)
00066 {
00067 boost::mutex::scoped_lock lock(mutex);
00068 obj_stack.insert(obj_stack.end(), vec.begin(), vec.end());
00069 vec.clear();
00070 }
00071
00072
00073 private:
00074 boost::mutex mutex;
00075 T* objects;
00076 std::vector<T*> obj_stack;
00077 unsigned overflow;
00078
00079 };
00080
00081 }
00082
00083 #endif