56 lines
1.2 KiB
C++
56 lines
1.2 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 _grow_size;
|
|
std::atomic<size_t> _outstanding;
|
|
public:
|
|
ConcurrentPool(size_t initial_size=256, size_t grow_size=32):
|
|
_all(), _free(), _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]};
|
|
for (size_t x = 0; x < count; ++x) {
|
|
T* temp = &buffer[x];
|
|
release(&temp);
|
|
}
|
|
_all.push_back(std::move(buffer));
|
|
}
|
|
|
|
void release(T**const item) {
|
|
if (*item) {
|
|
(*item)->reset();
|
|
_free.push(*item);
|
|
*item = nullptr;
|
|
--_outstanding;
|
|
}
|
|
}
|
|
|
|
};
|
|
|
|
}} //namespace
|