New MemoryPool tool

This commit is contained in:
Guilhem Lavaux 2012-05-18 18:16:13 -04:00
parent 7bd2ccbee4
commit 59de27a696
3 changed files with 115 additions and 0 deletions

View File

@ -22,6 +22,9 @@ target_link_libraries(testDelaunay ${tolink})
add_executable(testNewton testNewton.cpp) add_executable(testNewton testNewton.cpp)
target_link_libraries(testNewton ${tolink}) target_link_libraries(testNewton ${tolink})
add_executable(testPool testPool.cpp)
target_link_libraries(testPool ${tolink})
if (HDF5_FOUND) if (HDF5_FOUND)
add_executable(testReadFlash testReadFlash.cpp) add_executable(testReadFlash testReadFlash.cpp)
target_link_libraries(testReadFlash ${tolink}) target_link_libraries(testReadFlash ${tolink})

19
sample/testPool.cpp Normal file
View File

@ -0,0 +1,19 @@
#include "pool.hpp"
using namespace CosmoTool;
int main(int argc, char **argv)
{
MemoryPool<int> 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;
}

93
src/pool.hpp Normal file
View File

@ -0,0 +1,93 @@
#ifndef __COSMO_POOL_HPP
#define __COSMO_POOL_HPP
#include <list>
#include "config.hpp"
namespace CosmoTool
{
template<typename T>
struct PoolNode
{
T *data;
uint32_t last_free, size;
PoolNode<T> *next;
};
// This is bare simple memory pools
template<typename T>
class MemoryPool
{
private:
uint32_t m_allocSize;
PoolNode<T> *head, *current;
public:
MemoryPool(uint32_t allocSize)
: m_allocSize(allocSize), head(0), current(0) {}
~MemoryPool()
{
free_all();
}
void free_all()
{
PoolNode<T> *node = head;
while (node != 0)
{
PoolNode<T> *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 &current->data[current->last_free++];
}
T *alloc_new_in_node()
{
PoolNode<T> *newNode = new PoolNode<T>;
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