pool.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. #pragma once
  2. #include <iostream>
  3. #include <assert.h>
  4. #include <mutex>
  5. template<typename T>
  6. class Alloc_Pool
  7. {
  8. private:
  9. struct NODE
  10. {
  11. NODE* next;
  12. char t[sizeof(T)];
  13. };
  14. public:
  15. Alloc_Pool();
  16. ~Alloc_Pool();
  17. //T* Alloc();
  18. template<typename...X>
  19. T* Alloc(X...Args);
  20. void Free(T* ptr);
  21. static Alloc_Pool& GetInstance();
  22. private:
  23. bool InternalAlloc();
  24. NODE* Head;
  25. int m_BaseIndex;
  26. NODE* PtrBase[T::BASE_SIZE];
  27. NODE* next;
  28. std::mutex lock;
  29. };
  30. template<typename T>
  31. bool Alloc_Pool<T>::InternalAlloc()
  32. {
  33. NODE* p = NULL;
  34. if (m_BaseIndex < T::BASE_SIZE)
  35. p = PtrBase[m_BaseIndex++] = (NODE*)malloc(sizeof(NODE) * T::ALLOC_ARG);
  36. else
  37. {
  38. //p = (NODE*)malloc(sizeof(NODE)*T::ALLOC_ARG);
  39. assert(false);
  40. }
  41. if (p == NULL)
  42. {
  43. std::cout << "no memory" << std::endl;
  44. exit(0);
  45. return false;
  46. }
  47. for (int i = 0; i < T::ALLOC_ARG; i++)
  48. {
  49. if (Head == NULL)
  50. {
  51. Head = &p[i];
  52. Head->next = NULL;
  53. }
  54. else
  55. {
  56. p[i].next = Head;
  57. Head = &p[i];
  58. }
  59. }
  60. return true;
  61. }
  62. template<typename T>
  63. Alloc_Pool<T>::Alloc_Pool()
  64. {
  65. Head = NULL;
  66. m_BaseIndex = 0;
  67. //InitializeCriticalSection(&m_cs);
  68. InternalAlloc();
  69. }
  70. template<typename T>
  71. Alloc_Pool<T>::~Alloc_Pool()
  72. {
  73. for (int i = 0; i < m_BaseIndex; i++)
  74. free(PtrBase[i]);
  75. }
  76. template<typename T>
  77. template<typename...X>
  78. T* Alloc_Pool<T>::Alloc(X...Args)
  79. {
  80. std::lock_guard<std::mutex> lg(lock);
  81. if (Head == NULL)
  82. {
  83. InternalAlloc();
  84. }
  85. NODE* temp = Head;
  86. Head = Head->next;
  87. new(temp->t) T(Args...);
  88. return reinterpret_cast<T*>(temp->t);
  89. }
  90. template<typename T>
  91. Alloc_Pool<T>& Alloc_Pool<T>::GetInstance()
  92. {
  93. static Alloc_Pool<T> s;
  94. return s;
  95. }
  96. template<typename T>
  97. void Alloc_Pool<T>::Free(T* ptr)
  98. {
  99. ptr->~T();
  100. int8_t* p = (int8_t*)ptr;
  101. p -= sizeof(NODE*);
  102. NODE* node = (NODE*)p;
  103. std::lock_guard<std::mutex> lg(lock);
  104. node->next = Head;
  105. Head = node;
  106. }