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

70 lines
1.7 KiB
C++

#pragma once
#include <tbb/concurrent_queue.h>
#include <tbb/concurrent_vector.h>
#include <atomic>
namespace bts {
namespace utils {
template <class T>
class ConcurrentPool {
tbb::concurrent_vector<std::unique_ptr<T[]>> _all;
tbb::concurrent_queue<T*> _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() { }
T* allocate() {
T* result = nullptr;
++_outstanding;
if (_free.try_pop(result)) {
return result;
}
else {
reserve(_grow_size);
return allocate();
}
}
void reserve(size_t count) {
std::unique_ptr<T[]> buffer {new T[count]};
_outstanding += count;
for (size_t x = 0; x < count; ++x) {
T* temp = &buffer[x];
release(&temp);
}
_all.push_back(std::move(buffer));
}
void release(T** item) {
if (*item) {
(*item)->reset();
_free.push(*item);
*item = nullptr;
--_outstanding;
}
}
template <class CB>
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 std::unique_ptr<T[]>& bucket = *iter;
const T* start = bucket.get();
cb(start[x]);
}
}
}
};
}} //namespace