1 #include "memory_preallocated.h" 2 3 4 5 /* Initialise the memory pool with the given amount in bytes. */ 6 7 MemoryPreallocated::MemoryPreallocated(Memory *memory, offset_t amount) 8 : _memory(memory), _amount(amount) 9 { 10 // NOTE: Handle allocation failure. 11 12 offset_t remaining = amount; 13 14 while (remaining) 15 { 16 _regions.push_back(memory->region()); 17 18 if (memory->region_size() >= remaining) 19 break; 20 21 remaining -= memory->region_size(); 22 } 23 } 24 25 /* Discard all unused regions. */ 26 27 MemoryPreallocated::~MemoryPreallocated() 28 { 29 while (!_regions.empty()) 30 { 31 Region *region = _regions.front(); 32 33 _regions.pop_front(); 34 _memory->release(region); 35 } 36 } 37 38 /* Obtain an allocated region. */ 39 40 Region *MemoryPreallocated::region() 41 { 42 std::lock_guard<std::mutex> guard(_lock); 43 44 Region *region = _regions.front(); 45 46 _regions.pop_front(); 47 return region; 48 } 49 50 /* Release the allocated 'region'. */ 51 52 void MemoryPreallocated::release(Region *region) 53 { 54 std::lock_guard<std::mutex> guard(_lock); 55 56 _regions.push_back(region); 57 } 58 59 // vim: tabstop=4 expandtab shiftwidth=4