From 5fdb71c47bfb2daef6a15c15692d15a528bf17a9 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Tue, 18 Nov 2025 19:47:35 +0300 Subject: [PATCH] add ObjectsPool --- src/util/BufferPool.hpp | 2 -- src/util/ObjectsPool.hpp | 51 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 src/util/ObjectsPool.hpp diff --git a/src/util/BufferPool.hpp b/src/util/BufferPool.hpp index aeeebb8c..c3a1112d 100644 --- a/src/util/BufferPool.hpp +++ b/src/util/BufferPool.hpp @@ -5,8 +5,6 @@ #include #include -#include "typedefs.hpp" - namespace util { /// @brief Thread-safe pool of same-sized buffers /// @tparam T array type diff --git a/src/util/ObjectsPool.hpp b/src/util/ObjectsPool.hpp new file mode 100644 index 00000000..de3e30ae --- /dev/null +++ b/src/util/ObjectsPool.hpp @@ -0,0 +1,51 @@ +#pragma once + +#include +#include +#include +#include + +namespace util { + struct AlignedDeleter { + void operator()(void* p) const { + std::free(p); + } + }; + + template + class ObjectsPool { + public: + ObjectsPool(size_t preallocated = 0) { + for (size_t i = 0; i < preallocated; i++) { + allocateNew(); + } + } + + template + std::shared_ptr create(Args&&... args) { + std::lock_guard lock(mutex); + if (freeObjects.empty()) { + allocateNew(); + } + auto ptr = freeObjects.front(); + freeObjects.pop(); + new (ptr)T(std::forward(args)...); + return std::shared_ptr(reinterpret_cast(ptr), [this](T* ptr) { + std::lock_guard lock(mutex); + freeObjects.push(ptr); + }); + } + private: + std::vector> objects; + std::queue freeObjects; + std::mutex mutex; + + void allocateNew() { + std::unique_ptr ptr( + std::aligned_alloc(alignof(T), sizeof(T)) + ); + freeObjects.push(ptr.get()); + objects.push_back(std::move(ptr)); + } + }; +}