Asio游戏网络中间件设计(二)内存管理
目标
网络层中会产生大量内存碎片,而且频繁地申请内存也影响效率,所以需要设计内存池来管理。
为了避免线程context切换时的开销,设计中尽量避免使用锁。
对象池
namespace parallel_core
{
template<class T>
class ObjectPool
{
public:
ObjectPool();
~ObjectPool();
inline int countAll();
inline int countActive();
inline int countInactive();
template <class ... P>
inline T* get(P&& ... p);
inline void release(T* element);
inline void clear();
private:
std::atomic<int> _count;
Spinlock _lock;
std::stack<T*> _pool;
};
template<class T>
inline ObjectPool<T>::ObjectPool()
{
_count.store(0);
}
template<class T>
ObjectPool<T>::~ObjectPool()
{
clear();
}
template<class T>
inline int ObjectPool<T>::countAll()
{
return _count.load();
}
template<class T>
inline int ObjectPool<T>::countActive()
{
return _count.load() - countInactive();
}
template<class T>
inline int ObjectPool<T>::countInactive()
{
return _pool.size();
}
template<class T>
template <class ... P>
inline T* ObjectPool<T>::get(P&& ... p)
{
if (LIKELY(_pool.size() == 0))
{
_count++;
return new(std::nothrow) T(std::forward<P>(p) ...);
}
SpinlockHolder lk(&_lock);
T* ret = _pool.top();
_pool.pop();
return ret;
}
template<class T>
inline void ObjectPool<T>::