void main() { MPOOL_T mpool; int i=20; char *new_p1, *new_p2, *new_p3; void* arr_malloc[MAX_HANDLES]; char mem_1[500]; char mem_2[300]; mpool_init(&mpool, mem_1, sizeof(mem_1), 0, 4); new_p1 = mpool_malloc(mpool, 10); mpool_print(mpool); if (!new_p1) printf("%s", PROMPT_FAILED); mpool_grow(mpool,mem_2, sizeof(mem_2)); mpool_print(mpool); new_p2 = mpool_malloc(mpool, 32); if (!new_p2) printf("%s", PROMPT_FAILED); mpool_free(mpool, new_p2); mpool_print(mpool); new_p3 = mpool_malloc(mpool, 12); mpool_print(mpool); if (!new_p3) printf("%s", PROMPT_FAILED); mpool_free(mpool, new_p1); mpool_print(mpool); mpool_free(mpool, new_p2); mpool_print(mpool); mpool_free(mpool, new_p3); mpool_print(mpool); random_test(&mpool, arr_malloc, MAX_HANDLES, 10); lining_test(&mpool, arr_malloc, MAX_HANDLES); fixing_test(&mpool, arr_malloc, MAX_HANDLES); }
/* * fh_mpool_get * * Get an element from the memory pool. */ void *fh_mpool_get(fh_mpool_t *mp) { fh_mchunk_t *mc; void *e = NULL; FH_ASSERT(mp); if (mp->mp_flags & FH_MPOOL_FL_LOCK) { pthread_mutex_lock(&mp->mp_lock); } if (mp->mp_free == 0) { if (!(mp->mp_flags & FH_MPOOL_FL_GROW)) { fh_mpool_stats(mp); FH_LOG(CSI, ERR, ("pool '%s' is not growable: %d free elments", mp->mp_name, mp->mp_free)); goto end; } if (mpool_grow(mp) != FH_OK) { FH_LOG(CSI, ERR, ("ran out of chunks and couldn't grow the memory pool")); goto end; } } if (mp->mp_mchunks == NULL) { FH_LOG(CSI, ERR, ("MPOOL_GET: pool='%s': ran out of chunks: inuse %d free %d", mp->mp_name, mp->mp_inuse, mp->mp_free)); FH_ASSERT(1); } mc = mp->mp_mchunks; mp->mp_mchunks = mc->mc_next; mp->mp_inuse++; mp->mp_free--; if (mp->mp_flags & FH_MPOOL_FL_LOCK) { pthread_mutex_unlock(&mp->mp_lock); } e = (char *)mc + sizeof(fh_mchunk_t); FH_LOG(CSI, INFO, ("MPOOL_GET: pool='%s': chunk=%p inuse %d free %d", mp->mp_name, e, mp->mp_inuse, mp->mp_free)); end: if (mp->mp_flags & FH_MPOOL_FL_LOCK) { pthread_mutex_unlock(&mp->mp_lock); } return e; }
/* * fh_mpool_new * * Allocate and initialize a new memory pool of element of size 'chunk_size'. * The memory pool can be created to be lock-protected, growable, and to clear * memory when chunks are returned to pool. */ fh_mpool_t *fh_mpool_new(char *name, int chunk_size, int nchunks, int flags) { fh_mpool_t *mp = (fh_mpool_t *) malloc(sizeof(fh_mpool_t)); if (!mp) { FH_LOG(CSI, ERR, ("Couldn't allocate memory for the pool")); return NULL; } memset(mp, 0, sizeof(fh_mpool_t)); mp->mp_chunksize = chunk_size; mp->mp_nchunks = nchunks; mp->mp_flags = flags; mp->mp_mblocks = NULL; mp->mp_mchunks = NULL; if (mp->mp_flags & FH_MPOOL_FL_LOCK) { pthread_mutex_init(&mp->mp_lock, NULL); } mp->mp_name = strdup(name); if (!mp->mp_name) { FH_LOG(CSI, ERR, ("Couldn't allocate memory for pool name: %s", name)); fh_mpool_free(mp); return NULL; } mp->mp_inuse = 0; mp->mp_free = 0; if (mpool_grow(mp) != FH_OK) { FH_LOG(CSI, ERR, ("Couldn't allocate memory chunks")); fh_mpool_free(mp); return NULL; } return mp; }