반응형
내가 만든 module에 쓸 생각으로 간단한 pool을 만들었다.
일부러 library를 사용하려고 하였다.
#include <iostream>
#include <string>
#include <list>
#include <memory>
#include <stdexcept>
#include <vector>
#include <functional>
using namespace std;
static const int MAX = 32 * 1024;
template<class T>
using CallbackToRelease = std::function<void(shared_ptr<T> item)>;
class Item : public std::enable_shared_from_this<Item>
{
public:
Item(void) = delete;
Item(CallbackToRelease<Item> funcPtr) : releaseFuncPtr_(funcPtr)
{
}
virtual ~Item(void)
{
}
void Release(void)
{
releaseFuncPtr_(shared_from_this());
}
private:
CallbackToRelease<Item> releaseFuncPtr_;
};
template<class T>
class Pool : public std::enable_shared_from_this<Pool<T>>
{
public:
Pool(const string& poolName, const size_t poolSize)
: poolName_(poolName),
capacity_(poolSize)
{
auto callback = std::bind(&Pool<T>::Free, this, std::placeholders::_1);
all_.reserve(capacity_);
for (size_t i = 0; i < capacity_; ++i)
{
auto item = make_shared<T>(callback);
all_.emplace_back(item);
free_.emplace_back(item);
}
}
virtual ~Pool(void)
{
all_.clear();
free_.clear();
}
shared_ptr<T> Alloc(void)
{
if (free_.empty())
throw bad_alloc();
auto item = free_.front();
free_.pop_front();
return item;
}
void Free(shared_ptr<T> item)
{
free_.emplace_back(item);
}
size_t GetCapacity(void)
{
return capacity_;
}
size_t GetFreeCount(void)
{
return free_.size();
}
size_t GetUsedCount(void)
{
return capacity_ - GetFreeCount();
}
private:
list<shared_ptr<T>> free_;
vector<shared_ptr<T>> all_;
string poolName_;
size_t capacity_;
};
int main()
{
Pool<Item> pool("pool", MAX);
cout << "- initial status" << endl;
cout << "free cnt: " << pool.GetFreeCount() << endl;
cout << "used cnt: " << pool.GetUsedCount() << endl;
vector<shared_ptr<Item>> v;
for (size_t i = 0; i < MAX; ++i)
v.emplace_back(pool.Alloc());
cout << "- alloc " << MAX << endl;
cout << "free cnt: " << pool.GetFreeCount() << endl;
cout << "used cnt: " << pool.GetUsedCount() << endl;
cout << "- alloc once more" << endl;
try
{
pool.Alloc();
}
catch (std::bad_alloc& e)
{
cout << e.what() << endl;
}
for (auto item : v)
item->Release();
cout << "- free all" << endl;
cout << "free cnt: " << pool.GetFreeCount() << endl;
cout << "used cnt: " << pool.GetUsedCount() << endl;
return 0;
}
반응형
'프로그래밍 > C & C++' 카테고리의 다른 글
intel tbb::concurrent_queue를 이용해보기 (0) | 2022.01.09 |
---|---|
c++로 작성한 간단한 multi level queue (0) | 2022.01.08 |
[Effective C++] class를 사용할 때 초기화와 대입은 다르다 (0) | 2021.12.19 |
[C/VC] 간단한 Critical Section 테스트 (0) | 2011.03.06 |
댓글