pool.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. #pragma once
  2. #include <mutex>
  3. #include <assert.h>
  4. #include <iostream>
  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. assert(p!=nullptr);
  42. if (p == NULL)
  43. {
  44. std::cout << "no memory" << std::endl;
  45. exit(0);
  46. return false;
  47. }
  48. for (int i = 0; i < T::ALLOC_ARG; i++)
  49. {
  50. if (Head == NULL)
  51. {
  52. Head = &p[i];
  53. Head->next = NULL;
  54. }
  55. else
  56. {
  57. p[i].next = Head;
  58. Head = &p[i];
  59. }
  60. }
  61. return true;
  62. }
  63. template<typename T>
  64. Alloc_Pool<T>::Alloc_Pool()
  65. {
  66. Head = NULL;
  67. m_BaseIndex = 0;
  68. //InitializeCriticalSection(&m_cs);
  69. InternalAlloc();
  70. }
  71. template<typename T>
  72. Alloc_Pool<T>::~Alloc_Pool()
  73. {
  74. for (int i = 0; i < m_BaseIndex; i++)
  75. free(PtrBase[i]);
  76. }
  77. template<typename T>
  78. template<typename...X>
  79. T* Alloc_Pool<T>::Alloc(X...Args)
  80. {
  81. std::lock_guard<std::mutex> lg(lock);
  82. if (Head == NULL)
  83. {
  84. InternalAlloc();
  85. }
  86. NODE* temp = Head;
  87. Head = Head->next;
  88. new(temp->t) T(Args...);
  89. return reinterpret_cast<T*>(temp->t);
  90. }
  91. template<typename T>
  92. Alloc_Pool<T>& Alloc_Pool<T>::GetInstance()
  93. {
  94. static Alloc_Pool<T> s;
  95. return s;
  96. }
  97. template<typename T>
  98. void Alloc_Pool<T>::Free(T* ptr)
  99. {
  100. ptr->~T();
  101. int8_t* p = (int8_t*)ptr;
  102. p -= sizeof(NODE*);
  103. NODE* node = (NODE*)p;
  104. std::lock_guard<std::mutex> lg(lock);
  105. node->next = Head;
  106. Head = node;
  107. }