12 #ifndef SST_CORE_MEMPOOL_H
13 #define SST_CORE_MEMPOOL_H
25 #include "sst/core/threadsafe.h"
35 template <
typename LOCK_t>
38 std::vector<void*> list;
40 inline void insert(
void *ptr) {
41 std::lock_guard<LOCK_t> lock(mtx);
45 inline void* try_remove() {
46 std::lock_guard<LOCK_t> lock(mtx);
47 if ( list.empty() )
return NULL;
48 void *p = list.back();
53 size_t size()
const {
return list.size(); }
62 MemPool(
size_t elementSize,
size_t initialSize=(2<<20)) :
64 elemSize(elementSize), arenaSize(initialSize),
72 for ( std::list<uint8_t*>::iterator i = arenas.begin() ; i != arenas.end() ; ++i ) {
80 void *ret = freeList.try_remove();
82 bool ok = allocPool();
83 if ( !ok )
return NULL;
84 #if ( defined( __amd64 ) || defined( __amd64__ ) || \
85 defined( __x86_64 ) || defined( __x86_64__ ) )
87 #elif defined(__PPC64__)
88 asm volatile(
"or 27, 27, 27" :::
"memory" );
90 ret = freeList.try_remove();
97 inline void free(
void *ptr)
100 freeList.insert(ptr);
112 uint64_t bytes_in_arenas = arenas.size() * arenaSize;
113 uint64_t bytes_in_free_list = freeList.size() *
sizeof(
void*);
114 return bytes_in_arenas + bytes_in_free_list;
117 uint64_t getUndeletedEntries() {
126 size_t getArenaSize()
const {
return arenaSize; }
127 size_t getElementSize()
const {
return elemSize; }
129 const std::list<uint8_t*>& getArenas() {
return arenas; }
136 if ( allocating.exchange(1, std::memory_order_acquire) ) {
140 uint8_t *newPool = (uint8_t*)mmap(0, arenaSize, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
141 if ( MAP_FAILED == newPool ) {
142 allocating.store(0, std::memory_order_release);
145 std::memset(newPool, 0xFF, arenaSize);
146 arenas.push_back(newPool);
147 size_t nelem = arenaSize / elemSize;
148 for (
size_t i = 0 ; i < nelem ; i++ ) {
149 uint64_t* ptr = (uint64_t*)(newPool + (elemSize*i));
153 freeList.insert(ptr);
156 allocating.store(0, std::memory_order_release);
163 std::atomic<unsigned int> allocating;
164 FreeList<ThreadSafe::Spinlock> freeList;
165 std::list<uint8_t*> arenas;
MemPool(size_t elementSize, size_t initialSize=(2<< 20))
Create a new Memory Pool.
Definition: mempool.h:62
void free(void *ptr)
Return an element to the memory pool.
Definition: mempool.h:97
void * malloc()
Allocate a new element from the memory pool.
Definition: mempool.h:78
std::atomic< uint64_t > numAlloc
Counter: Number of times elements have been allocated.
Definition: mempool.h:122
uint64_t getBytesMemUsed()
Approximates the current memory usage of the mempool.
Definition: mempool.h:111
std::atomic< uint64_t > numFree
Counter: Number times elements have been freed.
Definition: mempool.h:124
Simple Memory Pool class.
Definition: mempool.h:33