// // Copyright @ 2014 Hangzhou Topzen Ltd. // Author: Yab Bin (yanb@es.zju.edu.cn) @ 2014-12 // #ifndef __OBJECTPOOL_H #define __OBJECTPOOL_H #include "BaseTypes.h" #include "BaseHeaders.h" #include "Locks.h" namespace tzc { template class ObjectPool { public: enum __OBJPOOL_ERROR { OPSucess = 0, OPNoFreeObj, OPNoTaskObj, OPEmptyPool }; public: ObjectPool(); ~ObjectPool(); // return 0 if successful, -1 while error occurs TZ_INT PopObj(T & Obj); TZ_INT PopFreeObj(T & Obj); TZ_INT PopTaskObj(T & Obj); void PushFreeObj(T & Obj); void PushTaskObj(T & Obj); TZ_INT GetFreeCnt(); TZ_INT GetTaskCnt(); TZ_INT GetOPError() const; private: void SetOPError(const TZ_INT errcode); private: Mutex m_mtxFreePool; std::list m_vFreePool; Mutex m_mtxTaskPool; std::list m_vTaskPool; TZ_INT m_OPErrno; }; template ObjectPool::ObjectPool(): m_OPErrno(OPSucess) { } template ObjectPool::~ObjectPool() { m_vFreePool.clear(); m_vTaskPool.clear(); } template TZ_INT ObjectPool::GetOPError() const { return m_OPErrno; } template void ObjectPool::SetOPError(const TZ_INT errcode) { m_OPErrno = errcode; } template TZ_INT ObjectPool::PopObj(T & Obj) { if (this->GetTaskCnt()) { return this->PopTaskObj(Obj); } if (this->GetFreeCnt()) { return this->PopFreeObj(Obj); } this->SetOPError(OPEmptyPool); return -1; } template TZ_INT ObjectPool::PopFreeObj(T & Obj) { m_mtxFreePool.Lock(); if(m_vFreePool.empty()) { m_mtxFreePool.Unlock(); this->SetOPError(OPNoFreeObj); return -1; } Obj = m_vFreePool.front(); m_vFreePool.pop_front(); m_mtxFreePool.Unlock(); this->SetOPError(OPSucess); return 0; } template TZ_INT ObjectPool::PopTaskObj(T & Obj) { m_mtxTaskPool.Lock(); if(m_vTaskPool.empty()) { m_mtxTaskPool.Unlock(); this->SetOPError(OPNoTaskObj); return -1; } Obj = m_vTaskPool.front(); m_vTaskPool.pop_front(); m_mtxTaskPool.Unlock(); this->SetOPError(OPSucess); return 0; } template void ObjectPool::PushFreeObj(T & Obj) { m_mtxFreePool.Lock(); m_vFreePool.push_back(Obj); m_mtxFreePool.Unlock(); } template void ObjectPool::PushTaskObj(T & Obj) { m_mtxTaskPool.Lock(); m_vTaskPool.push_back(Obj); m_mtxTaskPool.Unlock(); } template TZ_INT ObjectPool::GetFreeCnt() { m_mtxFreePool.Lock(); TZ_INT iTmpCount(m_vFreePool.size()); m_mtxFreePool.Unlock(); return iTmpCount; } template TZ_INT ObjectPool::GetTaskCnt() { m_mtxTaskPool.Lock(); TZ_INT iTmpCount(m_vTaskPool.size()); m_mtxTaskPool.Unlock(); return iTmpCount; } } // namespace tzc #endif /* ----- #ifndef __OBJECTPOOL_H ----- */