写了个objectpool,很简单,就是个线程安全的队列。
#pragma once
#include <iostream>
#include <concurrent_vector.h>
#include <concurrent_queue.h>
#include <algorithm>
template <typename T>
class ObjectPool
{
public:
ObjectPool(size_t chunk_size = kdefault_size, size_t chunk_num = 32)
: chunk_size_ (chunk_size)
, chunk_num_(chunk_num)
{
allocate_chunk();
}
~ObjectPool()
{
std::for_each(all_objects_.begin(), all_objects_.end(), ObjectPool<T>::array_delete_object);
}
T* acquire_object()
{
if (free_list_.empty())
{
allocate_chunk();
}
T *obj = nullptr;
free_list_.try_pop(obj);
return obj;
}
void release_object(T* obj)
{
if (NULL != obj)
free_list_.push(obj);
}
protected:
void allocate_chunk()
{
printf("%s\n", __FUNCTION__);
for (int i = 0; i < chunk_num_; ++i)
{
T* new_objects = new T(chunk_size_);
all_objects_.push_back(new_objects);
free_list_.push(new_objects);
}
}
static void array_delete_object(T* obj)
{
delete obj;
}
private:
Concurrency::concurrent_queue<T*> free_list_;
Concurrency::concurrent_vector<T*> all_objects_;
int chunk_size_; //对象池中预分配对象个数
int chunk_num_;
static const size_t kdefault_size = 100; //默认对象池大小
ObjectPool(const ObjectPool<T>& src);
ObjectPool<T>& operator=(const ObjectPool<T>& rhs);
};
#pragma once