1 /* 2 * A memory pool providing regions from a preallocated amount of memory. 3 * 4 * Copyright (C) 2021 Paul Boddie <paul@boddie.org.uk> 5 * 6 * This program is free software; you can redistribute it and/or 7 * modify it under the terms of the GNU General Public License as 8 * published by the Free Software Foundation; either version 2 of 9 * the License, or (at your option) any later version. 10 * 11 * This program is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 * GNU General Public License for more details. 15 * 16 * You should have received a copy of the GNU General Public License 17 * along with this program; if not, write to the Free Software 18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, 19 * Boston, MA 02110-1301, USA 20 */ 21 22 #include "memory_preallocated.h" 23 24 25 26 /* Initialise the memory pool with the given amount in bytes. */ 27 28 MemoryPreallocated::MemoryPreallocated(Memory *memory, offset_t amount) 29 : _memory(memory), _amount(amount) 30 { 31 // NOTE: Handle allocation failure. 32 33 offset_t remaining = amount; 34 35 while (remaining) 36 { 37 _regions.push_back(memory->region()); 38 39 if (memory->region_size() >= remaining) 40 break; 41 42 remaining -= memory->region_size(); 43 } 44 } 45 46 /* Discard all unused regions. */ 47 48 MemoryPreallocated::~MemoryPreallocated() 49 { 50 while (!_regions.empty()) 51 { 52 Region *region = _regions.front(); 53 54 _regions.pop_front(); 55 _memory->release(region); 56 } 57 } 58 59 /* Obtain an allocated region. */ 60 61 Region *MemoryPreallocated::region() 62 { 63 std::lock_guard<std::mutex> guard(_lock); 64 65 Region *region = _regions.front(); 66 67 _regions.pop_front(); 68 return region; 69 } 70 71 /* Release the allocated 'region'. */ 72 73 void MemoryPreallocated::release(Region *region) 74 { 75 std::lock_guard<std::mutex> guard(_lock); 76 77 _regions.push_back(region); 78 } 79 80 // vim: tabstop=4 expandtab shiftwidth=4