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

71 lines
1.6 KiB
C++

#pragma once
#include <atomic>
#include <tbb/concurrent_queue.h>
#include <tbb/concurrent_vector.h>
namespace bts {
namespace utils {
template <class T> class ConcurrentPool {
tbb::concurrent_vector<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() {
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 <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 T *start = *iter;
cb(start[x]);
}
}
}
};
} // namespace utils
} // namespace bts