#pragma once #include #include #include namespace bts { namespace utils { template class ConcurrentPool { tbb::concurrent_vector _all; tbb::concurrent_queue _free; size_t _initial_size; size_t _grow_size; size_t _outstanding; public: ConcurrentPool(size_t initial_size = 256, size_t grow_size = 32) : _all(), _free(), _initial_size(initial_size), _grow_size(grow_size), _outstanding(0) { reserve(initial_size); } ~ConcurrentPool() { for (auto b : _all) delete[] b; } T *allocate() { T *result = nullptr; ++_outstanding; if (_free.try_pop(result)) { return result; } else { reserve(_grow_size); return allocate(); } } void reserve(size_t count) { auto buffer = new T[count]; _outstanding += count; for (size_t x = 0; x < count; ++x) { T *temp = &buffer[x]; release(&temp); } _all.push_back(buffer); } void release(T **item) { if (*item) { (*item)->reset(); _free.push(*item); *item = nullptr; --_outstanding; } } template void unsafe_iterate(CB cb) const { for (auto iter = _all.begin(); iter != _all.end(); ++iter) { size_t size = (iter == _all.begin()) ? _initial_size : _grow_size; for (size_t x = 0; x < size; ++x) { const T *start = *iter; cb(start[x]); } } } }; } // namespace utils } // namespace bts