linux下一个内存池实现

来源:互联网 发布:钢筋工程量计算软件 编辑:程序博客网 时间:2024/04/30 19:45

memory_pool.h

#ifndef _MEMORY_POOL_H_#define _MEMORY_POOL_H_#ifdef __cplusplus    namespace mem_pool {  extern "C" {#endif/*Pool's mininum capacity*/#define MP_MIN_CAPACITY 5/*Pool's default capacity*/#define MP_DEF_CAPACITY 30/*Pool's maximum capacity*/#define MP_MAX_CAPACITY 100/*User-defined alloc & free routine*/typedef void *(*mp_alloc)();typedef void (*mp_free)(void *);/*memory pool structure*/typedef struct{int m_capacity;//Pool's capacityint m_itemcnt;//Pool's current item countvoid** m_items;//Pool's item pointer arraymp_alloc m_alloc;//Pool's alloc functionmp_free m_free;//Pool's free function}mp_t;/*Function: create a new memory poolParam:_alloc--------User-defined alloc function_free---------User_defined free function_capacity-----Pool's capacityReturn:A new memory pool if successful, NULL otherwiseNote:if _capacity is larger than MP_MAX_CAPACITY or smaller than MP_MIN_CAPACITY, MP_DEF_CAPACITY will be used*/mp_t* mempool_create(mp_alloc _alloc, mp_free _free, unsigned int _capacity);/*Function: destroy an existing memory poolParam:_mp--------the existing memory poolReturn:None*/void mempool_destroy(mp_t *_mp);/*Function: alloc a memory block from a memory poolParam:_mp--------the memory poolReturn:a pointer to the allocated memory block, or NULL if failed*/void *mempool_alloc(mp_t *_mp);/*Function: deallocate a memory block to the memory poolParam:_mp--------the memory pool_item------the memory block to be deallocatedReturn:NULL*/void mempool_free(mp_t *_mp, void *_item);#ifdef __cplusplus    }  }#endif#endif

memory_pool.c

#include <stdlib.h>#include "memory_pool.h"#ifdef __cplusplus    namespace mem_pool {  extern "C" {#endifmp_t* mempool_create(mp_alloc _alloc, mp_free _free, unsigned int _capacity){mp_t *mp = NULL;if(NULL == _alloc || NULL == _free) {return NULL;}if(_capacity < MP_MIN_CAPACITY || _capacity > MP_MAX_CAPACITY) {_capacity = MP_DEF_CAPACITY;}mp = malloc(sizeof(mp_t));if(NULL != mp){mp->m_capacity = _capacity;mp->m_itemcnt = 0;mp->m_items = (void **)malloc(sizeof(void *) * _capacity);mp->m_alloc = _alloc;mp->m_free = _free;if(NULL == mp->m_items){free(mp);mp = NULL;}}return mp;}void mempool_destroy(mp_t *_mp){register unsigned int i;if(NULL != _mp){if(_mp->m_items){for(i = 0; i < _mp->m_itemcnt; ++i){if(NULL != _mp->m_items[i]){_mp->m_free(_mp->m_items[i]);_mp->m_items[i] = NULL;}}free(_mp->m_items);_mp->m_items = NULL;}free(_mp);_mp = NULL;}}void *mempool_alloc(mp_t *_mp){void *item = NULL;if(NULL != _mp){item = _mp->m_itemcnt > 0 ? _mp->m_items[--_mp->m_itemcnt] : _mp->m_alloc();}return item;}void mempool_free(mp_t *_mp, void *_item){if(NULL != _mp && NULL != _item){if(_mp->m_itemcnt < _mp->m_capacity){_mp->m_items[_mp->m_itemcnt++] = _item;}else{_mp->m_free(_item);}}}#ifdef __cplusplus    }  }#endif
完整代码下载:http://download.csdn.net/detail/lxgwm2008/4951341

原创粉丝点击