template <typename T> class MemoryPool { public: MemoryPool(size_t size = EXPANSION_SIZE) { expandTheFreeList(size); } ~MemoryPool(); //allocate a T element from the free list. void* alloc(size_t size) { if (next == NULL) { expandTheFreeList(); } MemoryPool<T>* head = next; next = head->next; return head; } //return a T element to the free list. void free(void* doomed) { MemoryPool<T>* head = static_cast< MemoryPool<T>* > (doomed); head->next = next; next = head; }
private: //next element on the free list. MemoryPool<T>* next; //if the freelist is empty, expand it by this amount. enum {EXPANSION_SIZE = 32}; //add free elements to the free list void expandTheFreeList(int howMany = EXPANSION_SIZE); };
template <typename POOLTYPE, typename LOCK> class MTMemoryPool { public: //allocate an element from the freelist. void* alloc(size_t size) { void* mem; theLock.lock(); mem = stPool.alloc(size); theLock.unlock(); return mem; }
//return an element to the freelist void free(void* someElement) { theLock.lock(); stPool.free(someElement); theLock.unlock(); }
private: POOLTYPE stPool;//Single-threaded pool. LOCK theLock; };
template <typename T> class MemoryPool { public: MemoryPool(size_t size = EXPANSION_SIZE) { expandTheFreeList(size); } ~MemoryPool(); //allocate a T element from the free list. void* alloc(size_t size) { if (next == NULL) { expandTheFreeList(); } MemoryPool<T>* head = next; next = head->next; return head; } //return a T element to the free list. void free(void* doomed) { MemoryPool<T>* head = static_cast< MemoryPool<T>* > (doomed); head->next = next; next = head; }
private: //next element on the free list. MemoryPool<T>* next; //if the freelist is empty, expand it by this amount. enum {EXPANSION_SIZE = 32}; //add free elements to the free list void expandTheFreeList(int howMany = EXPANSION_SIZE); };
template <typename POOLTYPE, typename LOCK> class MTMemoryPool { public: //allocate an element from the freelist. void* alloc(size_t size) { void* mem; theLock.lock(); mem = stPool.alloc(size); theLock.unlock(); return mem; }
//return an element to the freelist void free(void* someElement) { theLock.lock(); stPool.free(someElement); theLock.unlock(); }
private: POOLTYPE stPool;//Single-threaded pool. LOCK theLock; };