1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/memory_preallocated.cc Sat Mar 20 01:41:43 2021 +0100
1.3 @@ -0,0 +1,53 @@
1.4 +#include "memory_preallocated.h"
1.5 +
1.6 +/* Initialise the memory pool with a mandatory 'limit' in pages. */
1.7 +
1.8 +MemoryPreallocated::MemoryPreallocated(unsigned int limit, offset_t region_size)
1.9 +: Memory(region_size), _limit(limit)
1.10 +{
1.11 + while (limit > 0)
1.12 + {
1.13 + Region *r = region();
1.14 +
1.15 + if (r != NULL)
1.16 + _free.push_back(r);
1.17 + else
1.18 + break;
1.19 +
1.20 + limit--;
1.21 + }
1.22 +}
1.23 +
1.24 +/* Allocate a new region of the configured size rounded to the nearest page. */
1.25 +
1.26 +Region *MemoryPreallocated::region()
1.27 +{
1.28 + std::lock_guard<std::mutex> guard(_lock);
1.29 +
1.30 + std::list<Region *>::iterator it = _free.begin();
1.31 +
1.32 + if (it == _free.end())
1.33 + return NULL;
1.34 +
1.35 + Region *r = *it;
1.36 +
1.37 + _free.erase(it);
1.38 + _used.insert(r);
1.39 +}
1.40 +
1.41 +/* Release the allocated 'region'. */
1.42 +
1.43 +void MemoryPreallocated::release(Region *region)
1.44 +{
1.45 + std::lock_guard<std::mutex> guard(_lock);
1.46 +
1.47 + std::set<Region *>::iterator it = _used.find(region);
1.48 +
1.49 + if (it != _used.end())
1.50 + {
1.51 + _used.erase(it);
1.52 + _free.push_back(region);
1.53 + }
1.54 +}
1.55 +
1.56 +// vim: tabstop=4 expandtab shiftwidth=4