C++自动回收型内存池

  • Post author:
  • Post category:其他


#include <iostream>
#include <vector>
#include <memory>
#include <future>


template<typename ObjType>
class ObjectPool {
public:
	ObjectPool()
	{
	}

	virtual ~ObjectPool()
	{
		for (auto obj : m_CachePool) {
			free(obj);
		}
	}

public:
	template<typename T>
	using obj_unique_ptr = std::unique_ptr<T, std::function<void(T*)>>;

	template<typename... Args>
	obj_unique_ptr<ObjType> createUniqueObj(Args... args)
	{
		ObjType* pObj = createObj(args...);

		return obj_unique_ptr<ObjType>(
			pObj,
			[&](ObjType* obj) {
				this->releaseObj(obj);		
			});
	}

	template<typename... Args>
	ObjType* createObj(Args... args)
	{
		ObjType* pObj = nullptr;
		if (m_CachePool.size() == 0) {
			++m_AllocSize;
			pObj = (ObjType*)malloc(sizeof(ObjType));
		}
		else {
			pObj = m_CachePool.back();
			m_CachePool.pop_back();
		}
		new (pObj) ObjType(args...);
		return pObj;
	}

	void releaseObj(ObjType* pObj)
	{
		pObj->~ObjType();
		m_CachePool.push_back(pObj);

		// recycle
		if (m_AllocSize >= 1 / m_recyleRemain && 1.f * m_CachePool.size() / m_AllocSize > m_recyleThreshold) {
			m_recycleThread = std::async(
				[&]() {
					this->recycle(m_AllocSize * m_recyleRemain);
				});
		}
	}

	void recycle(size_t left)
	{
		while (true) {
			if (m_CachePool.size() <= left) {
				break;
			}

			ObjType* pObj = m_CachePool.back();
			m_CachePool.pop_back();
			--m_AllocSize;

			free(pObj);
		}
	}

protected:
	std::vector<ObjType*> m_CachePool;
	std::future<void> m_recycleThread;
	size_t m_AllocSize = 0;
	float m_recyleThreshold = 0.8;
	float m_recyleRemain = 0.1;
};


int main()
{
	auto start = std::chrono::high_resolution_clock::now();
	{
		std::vector<std::future<void>> f;
		for (int i = 0; i < 8; ++i) {
			f.push_back(
				std::async([]() {
					ObjectPool<int> pool;
					std::shared_ptr<int> p;
					for (int i = 0; i < 1e6; ++i) {
						auto obj = pool.createUniqueObj(666);
						//p = std::move(obj);
					}
					}
				)
			);
		}
	}
	auto passed = std::chrono::high_resolution_clock::now() - start;
	auto time = passed.count() / 1e9;
	std::cout << time << std::endl;
}



版权声明:本文为Benjaminzhou93原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。