From 59de27a69603a92e34a93e2c9b918d4c813f8a7b Mon Sep 17 00:00:00 2001 From: Guilhem Lavaux Date: Fri, 18 May 2012 18:16:13 -0400 Subject: [PATCH] New MemoryPool tool --- sample/CMakeLists.txt | 3 ++ sample/testPool.cpp | 19 +++++++++ src/pool.hpp | 93 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 115 insertions(+) create mode 100644 sample/testPool.cpp create mode 100644 src/pool.hpp diff --git a/sample/CMakeLists.txt b/sample/CMakeLists.txt index 82eabcd..d24f32d 100644 --- a/sample/CMakeLists.txt +++ b/sample/CMakeLists.txt @@ -22,6 +22,9 @@ target_link_libraries(testDelaunay ${tolink}) add_executable(testNewton testNewton.cpp) target_link_libraries(testNewton ${tolink}) +add_executable(testPool testPool.cpp) +target_link_libraries(testPool ${tolink}) + if (HDF5_FOUND) add_executable(testReadFlash testReadFlash.cpp) target_link_libraries(testReadFlash ${tolink}) diff --git a/sample/testPool.cpp b/sample/testPool.cpp new file mode 100644 index 0000000..ee01468 --- /dev/null +++ b/sample/testPool.cpp @@ -0,0 +1,19 @@ +#include "pool.hpp" + +using namespace CosmoTool; + +int main(int argc, char **argv) +{ + MemoryPool pool(1024); + int **j = new int *[3000]; + + for (int i = 0; i < 3000; i++) + { + j[i] = pool.alloc(); + j[i][0] = i; + } + + pool.free_all(); + + return 0; +} diff --git a/src/pool.hpp b/src/pool.hpp new file mode 100644 index 0000000..235a092 --- /dev/null +++ b/src/pool.hpp @@ -0,0 +1,93 @@ +#ifndef __COSMO_POOL_HPP +#define __COSMO_POOL_HPP + +#include +#include "config.hpp" + +namespace CosmoTool +{ + + template + struct PoolNode + { + T *data; + uint32_t last_free, size; + PoolNode *next; + }; + + // This is bare simple memory pools + template + class MemoryPool + { + private: + uint32_t m_allocSize; + PoolNode *head, *current; + public: + MemoryPool(uint32_t allocSize) + : m_allocSize(allocSize), head(0), current(0) {} + + ~MemoryPool() + { + free_all(); + } + + void free_all() + { + PoolNode *node = head; + + while (node != 0) + { + PoolNode *next = node->next; + + delete[] node->data; + delete node; + node = next; + } + current = head = 0; + } + + T *alloc() + { + T *ret = alloc_in_node(); + return (ret == 0) ? alloc_new_in_node() : ret; + } + + protected: + T *alloc_in_node() + { + if (current == 0 || current->last_free == current->size) + return 0; + return ¤t->data[current->last_free++]; + } + + T *alloc_new_in_node() + { + PoolNode *newNode = new PoolNode; + if (newNode == 0) + return 0; + + newNode->last_free = 1; + newNode->size = m_allocSize; + newNode->data = new T[m_allocSize]; + if (newNode->data == 0) + { + delete newNode; + return 0; + } + newNode->next = 0; + + if (current == 0) + current = head = newNode; + else + { + current->next = newNode; + current = newNode; + } + return &newNode->data[0]; + } + + }; + +}; + +#endif