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;
83 #if ( defined( __amd64 ) || defined( __amd64__ ) || \
84 defined( __x86_64 ) || defined( __x86_64__ ) )
86 #elif defined(__PPC64__)
87 asm volatile(
"or 27, 27, 27" :::
"memory" );
89 ret = freeList.try_remove();
96 inline void free(
void *ptr)
111 uint64_t bytes_in_arenas = arenas.size() * arenaSize;
112 uint64_t bytes_in_free_list = freeList.size() *
sizeof(
void*);
113 return bytes_in_arenas + bytes_in_free_list;
116 uint64_t getUndeletedEntries() {
125 size_t getArenaSize()
const {
return arenaSize; }
126 size_t getElementSize()
const {
return elemSize; }
128 const std::list<uint8_t*>& getArenas() {
return arenas; }
135 if ( allocating.exchange(1, std::memory_order_acquire) ) {
139 uint8_t *newPool = (uint8_t*)mmap(
nullptr, arenaSize, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
140 if ( MAP_FAILED == newPool ) {
141 allocating.store(0, std::memory_order_release);
144 std::memset(newPool, 0xFF, arenaSize);
145 arenas.push_back(newPool);
146 size_t nelem = arenaSize / elemSize;
147 for (
size_t i = 0 ; i < nelem ; i++ ) {
148 uint64_t* ptr = (uint64_t*)(newPool + (elemSize*i));
152 freeList.insert(ptr);
155 allocating.store(0, std::memory_order_release);
162 std::atomic<unsigned int> allocating;
163 FreeList<ThreadSafe::Spinlock> freeList;
164 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:96
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:121
uint64_t getBytesMemUsed()
Approximates the current memory usage of the mempool.
Definition: mempool.h:110
std::atomic< uint64_t > numFree
Counter: Number times elements have been freed.
Definition: mempool.h:123
Simple Memory Pool class.
Definition: mempool.h:32