1 #ifndef MARS_MemoryManager 2 #define MARS_MemoryManager 5 #include <forward_list> 10 class condition_variable;
11 template<
class T>
class shared_ptr<T>;
12 template<
class T>
class forward_list<T>;
36 MemoryStock(
size_t chunk,
size_t max) : fChunkSize(chunk), fMaxMemory(max<chunk?chunk:max),
37 fInUse(0), fAllocated(0), fMaxInUse(0)
42 std::shared_ptr<char>
pop(
bool block)
48 std::unique_lock<std::mutex> lock(fMutexCond);
49 while (fMemoryStock.empty() && fAllocated+fChunkSize>fMaxMemory)
56 if (fMemoryStock.empty() && fAllocated+fChunkSize>fMaxMemory)
57 return std::shared_ptr<char>();
66 if (fMemoryStock.empty())
69 fAllocated += fChunkSize;
70 return std::shared_ptr<char>(
new char[fChunkSize]);
74 const std::lock_guard<std::mutex> lock(fMutexMem);
76 const auto mem = fMemoryStock.front();
77 fMemoryStock.pop_front();
81 void push(
const std::shared_ptr<char> &mem)
91 if (fAllocated>fMaxMemory)
93 fAllocated -= fChunkSize;
98 const std::lock_guard<std::mutex> lock(fMutexMem);
99 fMemoryStock.emplace_front(mem);
103 const std::lock_guard<std::mutex> lock(fMutexCond);
119 fPointer = fMemoryStock->pop(block);
125 fMemoryStock->push(fPointer);
138 std::shared_ptr<char>
malloc(
bool block=
true)
140 const std::shared_ptr<MemoryChunk> chunk(
new MemoryChunk(fMemoryStock, block));
141 return std::shared_ptr<char>(chunk, chunk->fPointer.get());
149 throw std::runtime_error(
"Cannot change the chunk size while there is memory in use");
150 if (getMaxMemory()<size)
151 throw std::runtime_error(
"Chunk size ("+std::to_string((
long long int)size)+
") larger than allowed memory ("+std::to_string((
long long int)getMaxMemory())+
")");
153 if (getInUse() || getMaxMemory()<size)
157 fMemoryStock->fChunkSize =
size;
162 size_t getInUse()
const {
return fMemoryStock->fInUse; }
std::shared_ptr< char > malloc(bool block=true)
size_t getMaxInUse() const
std::shared_ptr< MemoryStock > fMemoryStock
MemoryChunk(const std::shared_ptr< MemoryStock > &mem, bool block)
MemoryStock(size_t chunk, size_t max)
size_t getAllocated() const
std::shared_ptr< MemoryStock > fMemoryStock
std::condition_variable fCond
std::shared_ptr< char > pop(bool block)
size_t getMaxMemory() const
size_t getChunkSize() const
MemoryManager(size_t chunk, size_t max)
std::forward_list< std::shared_ptr< char > > fMemoryStock
bool setChunkSize(const size_t size)
std::shared_ptr< char > fPointer
void push(const std::shared_ptr< char > &mem)