1
0

hobjectpool.h 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. #ifndef HV_OBJECT_POOL_H_
  2. #define HV_OBJECT_POOL_H_
  3. #include <list>
  4. #include <memory>
  5. #include <mutex>
  6. #include <condition_variable>
  7. #define DEFAULT_OBJECT_POOL_SIZE 4
  8. #define DEFAULT_GET_TIMEOUT 3000 // ms
  9. template<typename T>
  10. class HObjectPool {
  11. public:
  12. HObjectPool(int size = DEFAULT_OBJECT_POOL_SIZE)
  13. : pool_size(size), timeout(DEFAULT_GET_TIMEOUT), object_num(0) {
  14. }
  15. ~HObjectPool() {
  16. }
  17. virtual bool CreateObject(std::shared_ptr<T>& pObj) {
  18. pObj = std::shared_ptr<T>(new T);
  19. return true;
  20. }
  21. virtual bool InitObject(std::shared_ptr<T>& pObj) {
  22. return true;
  23. }
  24. std::shared_ptr<T> TryGet() {
  25. std::shared_ptr<T> pObj = NULL;
  26. std::lock_guard<std::mutex> locker(mutex_);
  27. if (!objects_.empty()) {
  28. pObj = objects_.front();
  29. objects_.pop_front();
  30. }
  31. return pObj;
  32. }
  33. std::shared_ptr<T> Get() {
  34. std::shared_ptr<T> pObj = TryGet();
  35. if (pObj) {
  36. return pObj;
  37. }
  38. std::unique_lock<std::mutex> locker(mutex_);
  39. if (object_num < pool_size) {
  40. if (CreateObject(pObj) && InitObject(pObj)) {
  41. ++object_num;
  42. return pObj;
  43. }
  44. }
  45. if (timeout > 0) {
  46. std::cv_status status = cond_.wait_for(locker, std::chrono::milliseconds(timeout));
  47. if (status == std::cv_status::timeout) {
  48. return NULL;
  49. }
  50. if (!objects_.empty()) {
  51. pObj = objects_.front();
  52. objects_.pop_front();
  53. return pObj;
  54. }
  55. else {
  56. // WARN: objects too little
  57. }
  58. }
  59. return pObj;
  60. }
  61. void Release(std::shared_ptr<T>& pObj) {
  62. objects_.push_back(pObj);
  63. cond_.notify_one();
  64. }
  65. bool Add(std::shared_ptr<T>& pObj) {
  66. std::lock_guard<std::mutex> locker(mutex_);
  67. if (object_num >= pool_size) {
  68. return false;
  69. }
  70. objects_.push_back(pObj);
  71. ++object_num;
  72. cond_.notify_one();
  73. return true;
  74. }
  75. bool Remove(std::shared_ptr<T>& pObj) {
  76. std::lock_guard<std::mutex> locker(mutex_);
  77. auto iter = objects_.begin();
  78. while (iter != objects_.end()) {
  79. if (*iter == pObj) {
  80. iter = objects_.erase(iter);
  81. --object_num;
  82. return true;
  83. }
  84. }
  85. return false;
  86. }
  87. void RemoveAll() {
  88. std::lock_guard<std::mutex> locker(mutex_);
  89. objects_.clear();
  90. }
  91. int pool_size;
  92. int timeout;
  93. private:
  94. int object_num;
  95. std::list<std::shared_ptr<T>> objects_;
  96. std::mutex mutex_;
  97. std::condition_variable cond_;
  98. };
  99. #endif // HV_OBJECT_POOL_H_