Files
spark/src/lib/utils/object_pool.h
T

58 lines
1.6 KiB
C++

#pragma once
#include "lib/utils/bts_assert.h"
#include "lib/utils/type_name.h"
#include <atomic>
#include <boost/pool/object_pool.hpp>
namespace bts::utils {
static inline std::atomic<std::uint16_t> instance_id_counter = 0;
template <typename T>
class object_pool {
std::atomic<std::size_t> count = 0;
std::size_t max_count = 128;
std::uint16_t instance_id = ++instance_id_counter;
std::size_t log_freq = 0;
std::string name;
boost::object_pool<T> pool;
public:
object_pool() : name(bts::utils::type_name<T>()) {}
object_pool(std::string name, std::size_t max_count, std::size_t log_freq)
: name(std::move(name)), max_count(max_count), log_freq(log_freq) {}
void set_max_count(std::size_t value) { max_count = value; }
void set_log_freq(std::uint16_t value) { log_freq = value; }
T *construct() {
std::size_t n = ++count;
bts_assert_msgf(
n < max_count, "n < max_count. {} < {}. name: {}; id: {}", n,
max_count, name, instance_id);
if (log_freq == 0 || n % log_freq == 0) {
LOG(Gen, Info, "object_pool::construct. name: {}; id: {}; count: {}",
name, instance_id, n);
}
return pool.construct();
}
void destroy(T *const p) {
std::size_t n = --count;
bts_assert_msgf(
n < max_count, "n < max_count. {} < {}. name: {}; id: {}", n,
max_count, name, instance_id);
if (log_freq == 0 || n % log_freq == 0) {
LOG(Gen, Info, "object_pool::destroy. name: {}; id: {}; count: {}",
name, instance_id, n);
}
pool.destroy(p);
}
};
} // namespace bts::utils