Last active
September 21, 2025 18:51
-
-
Save PackmanDude/cc28ef96a4c53b1023730a8d71025b5c to your computer and use it in GitHub Desktop.
A memory pooling library. (WIP)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #ifndef MPOOL_LIB | |
| #define MPOOL_LIB | |
| #ifdef __has_builtin | |
| # if __has_builtin(__builtin_expect) | |
| # define unlikely(condition) __builtin_expect((condition), 0) | |
| # else | |
| # define unlikely(condition) (condition) | |
| # endif | |
| #endif | |
| #include <errno.h> | |
| #include <pthread.h> | |
| #include <stdlib.h> | |
| #ifndef MEMORY_POOL_SIZE | |
| # define MEMORY_POOL_SIZE 256 | |
| #endif | |
| static struct MPoolRegion | |
| { | |
| void *data; | |
| size_t region_size; | |
| } memory_pool[MEMORY_POOL_SIZE]; | |
| static pthread_mutex_t memory_pool_mutex = PTHREAD_MUTEX_INITIALIZER; | |
| void * | |
| mpool_retrieve(size_t size) | |
| { | |
| int ret = pthread_mutex_lock(&memory_pool_mutex); | |
| if (unlikely(ret)) | |
| { | |
| errno = ret; | |
| return NULL; | |
| } | |
| for (size_t i = 0; i < MEMORY_POOL_SIZE; ++i) | |
| { | |
| if (memory_pool[i].region_size >= size) | |
| { | |
| memory_pool[i].data = NULL; | |
| memory_pool[i].region_size = 0; | |
| ret = pthread_mutex_unlock(&memory_pool_mutex); | |
| if (unlikely(ret)) | |
| { | |
| errno = ret; | |
| return NULL; | |
| } | |
| return memory_pool[i].data; | |
| } | |
| } | |
| ret = pthread_mutex_unlock(&memory_pool_mutex); | |
| if (unlikely(ret)) | |
| { | |
| errno = ret; | |
| return NULL; | |
| } | |
| return malloc(size); | |
| } | |
| void | |
| mpool_leave(void * restrict region, size_t size) | |
| { | |
| int ret = pthread_mutex_lock(&memory_pool_mutex); | |
| if (unlikely(ret)) | |
| { | |
| errno = ret; | |
| return; | |
| } | |
| for (size_t i = 0; i < MEMORY_POOL_SIZE; ++i) | |
| { | |
| if (!memory_pool[i].data) | |
| { | |
| memory_pool[i].data = region; | |
| memory_pool[i].region_size = size; | |
| break; | |
| } | |
| } | |
| ret = pthread_mutex_unlock(&memory_pool_mutex); | |
| if (unlikely(ret)) errno = ret; | |
| } | |
| #endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment