template <typename T, size_t ChunkSize = 5>
class MemoryPool
{
public:
MemoryPool() : m_usedSize(0), m_poolSize(0)
{
allocateChunk();
}
~MemoryPool()
{
for (auto chunk : m_chunks)
{
delete[] chunk;
}
}
T *allocate(bool blocking = true)
{
std::unique_lock<std::mutex> lock(m_mutex);
if (m_freeList.empty())
{
if (blocking)
{
m_cv.wait(lock, [this]()
{ return !m_freeList.empty(); });
}
else
{
allocateChunk();
// return nullptr;
}
}
T *object = m_freeList.back();
m_freeList.pop_back();
m_usedSize++;
return object;
}
void deallocate(T *object)
{
std::unique_lock<std::mutex> lock(m_mutex);
m_freeList.emplace_back(object);
m_cv.notify_one();
m_usedSize--;
}
size_t get_pool_size()
{
std::unique_lock<std::mutex> lock(m_mutex);
return m_poolSize;
}
size_t get_used_size()
{
std::unique_lock<std::mutex> lock(m_mutex);
return m_usedSize;
}
private:
void allocateChunk()
{
T *chunk = new T[ChunkSize];
m_chunks.emplace_back(chunk);
for (size_t i = 0; i < ChunkSize; ++i)
{
m_freeList.emplace_back(&chunk[i]);
}
m_poolSize += ChunkSize;
}
private:
std::vector<T *> m_chunks;
std::vector<T *> m_freeList;
std::mutex m_mutex;
std::condition_variable m_cv;
size_t m_poolSize;
size_t m_usedSize;
};
C++数据池模板类实现
于 2023-09-22 14:34:01 首次发布