12 #ifndef SST_CORE_MEMPOOL_H
13 #define SST_CORE_MEMPOOL_H
24 #include "sst/core/threadsafe.h"
34 template <
typename LOCK_t>
37 std::vector<void*> list;
39 inline void insert(
void *ptr) {
40 std::lock_guard<LOCK_t> lock(mtx);
44 inline void* try_remove() {
45 std::lock_guard<LOCK_t> lock(mtx);
46 if ( list.empty() )
return nullptr;
47 void *p = list.back();
52 size_t size()
const {
return list.size(); }
61 MemPool(
size_t elementSize,
size_t initialSize=(2<<20)) :
63 elemSize(elementSize), arenaSize(initialSize),
71 for ( std::list<uint8_t*>::iterator i = arenas.begin() ; i != arenas.end() ; ++i ) {
79 void *ret = freeList.try_remove();
81 bool ok = allocPool();
82 if ( !ok )
return nullptr;
84 ret = freeList.try_remove();
91 inline void free(
void *ptr)
106 uint64_t bytes_in_arenas = arenas.size() * arenaSize;
107 uint64_t bytes_in_free_list = freeList.size() *
sizeof(
void*);
108 return bytes_in_arenas + bytes_in_free_list;
111 uint64_t getUndeletedEntries() {
120 size_t getArenaSize()
const {
return arenaSize; }
121 size_t getElementSize()
const {
return elemSize; }
123 const std::list<uint8_t*>& getArenas() {
return arenas; }
130 if ( allocating.exchange(1, std::memory_order_acquire) ) {
134 uint8_t *newPool = (uint8_t*)mmap(
nullptr, arenaSize, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
135 if ( MAP_FAILED == newPool ) {
136 allocating.store(0, std::memory_order_release);
139 std::memset(newPool, 0xFF, arenaSize);
140 arenas.push_back(newPool);
141 size_t nelem = arenaSize / elemSize;
142 for (
size_t i = 0 ; i < nelem ; i++ ) {
143 uint64_t* ptr = (uint64_t*)(newPool + (elemSize*i));
147 freeList.insert(ptr);
150 allocating.store(0, std::memory_order_release);
157 std::atomic<unsigned int> allocating;
158 FreeList<ThreadSafe::Spinlock> freeList;
159 std::list<uint8_t*> arenas;
MemPool(size_t elementSize, size_t initialSize=(2<< 20))
Create a new Memory Pool.
Definition: mempool.h:61
void free(void *ptr)
Return an element to the memory pool.
Definition: mempool.h:91
void * malloc()
Allocate a new element from the memory pool.
Definition: mempool.h:77
std::atomic< uint64_t > numAlloc
Counter: Number of times elements have been allocated.
Definition: mempool.h:116
uint64_t getBytesMemUsed()
Approximates the current memory usage of the mempool.
Definition: mempool.h:105
std::atomic< uint64_t > numFree
Counter: Number times elements have been freed.
Definition: mempool.h:118
Simple Memory Pool class.
Definition: mempool.h:32