SPHinXsys  alpha version
my_memory_pool.h
1 #ifndef MY_MEMORY_POOL_H
2 #define MY_MEMORY_POOL_H
3 
4 #define TBB_PREVIEW_MEMORY_POOL 1
5 
6 #include "tbb/memory_pool.h"
7 #include "tbb/enumerable_thread_specific.h"
8 
9 #include <list>
10 
11 using namespace tbb;
16 template <class T>
18 {
19 
20 #ifdef __EMSCRIPTEN__
21  std::allocator<T> my_pool; // memory pool
22  std::list<T> data_list; // list of all nodes allocated
23 #else
24  tbb::memory_pool<std::allocator<T>> my_pool; // memory pool
25  typedef tbb::memory_pool_allocator<T> pool_allocator_t; // memory allocator
26  std::list<T, pool_allocator_t> data_list; // list of all nodes allocated
27 #endif
28  std::list<T *> free_list; // list of all free nodes
29 
30 public:
31  // constructor
32 #ifdef __EMSCRIPTEN__
33  MyMemoryPool() : data_list(my_pool){};
34 #else
35  MyMemoryPool() : data_list(pool_allocator_t(my_pool)){};
36 #endif
37  // deconstructor
38  ~MyMemoryPool(){
39  // my_pool.recycle();
40  };
41  // prepare an available node
42  T *malloc()
43  {
44  if (free_list.empty())
45  {
46  data_list.emplace_back(T());
47  return (&data_list.back());
48  }
49  else
50  {
51  T *result = free_list.front();
52  free_list.pop_front();
53  return result;
54  }
55  };
56  // relinquish an unused node
57  void free(T *ptr)
58  {
59  free_list.push_back(ptr);
60  };
61  // return the total number of nodes allocated
62  int capacity()
63  {
64  return data_list.size();
65  };
66  // return the number of current available nodes
67  int available_node()
68  {
69  return free_list.size();
70  };
71 };
72 
73 #endif // MY_MEMORY_POOL_H
Definition: particle_sorting.h:38
Note that the data package T should has a default constructor.
Definition: my_memory_pool.h:17