본문 바로가기
프로그래밍/C & C++

c++로 작성한 간단한 pool

by 체리 2022. 1. 8.
반응형

내가 만든 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;
}
반응형

댓글