本帖最后由 Simon21ic 于 2016-1-22 15:55 编辑
直接上代码,不多说了
头文件:
// pool
struct vsfpool_t
{
uint32_t *flags;
void *buffer;
uint32_t size;
uint32_t num;
};
#define VSFPOOL_DEFINE(name, type, num) \
struct vsfpool_##name##_t\
{\
struct vsfpool_t pool;\
uint32_t mskarr[((num) + 31) >> 5];\
type buffer[(num)];\
} name
#define VSFPOOL_INIT(p, type, n) \
do {\
(p)->pool.flags = (p)->mskarr;\
(p)->pool.buffer = (p)->buffer;\
(p)->pool.size = sizeof(type);\
(p)->pool.num = (n);\
vsfpool_init((struct vsfpool_t *)(p));\
} while (0)
#define VSFPOOL_ALLOC(p, type) \
(type *)vsfpool_alloc((struct vsfpool_t *)(p))
#define VSFPOOL_FREE(p, buf) \
vsfpool_free((struct vsfpool_t *)(p), (buf))
void vsfpool_init(struct vsfpool_t *pool);
void* vsfpool_alloc(struct vsfpool_t *pool);
void vsfpool_free(struct vsfpool_t *pool, void *buffer);
C文件
// pool
void vsfpool_init(struct vsfpool_t *pool)
{
memset(pool->flags, 0, (pool->num + 31) >> 3);
}
void* vsfpool_alloc(struct vsfpool_t *pool)
{
int index = mskarr_ffz(pool->flags, (pool->num + 31) >> 5);
if (index >= pool->num)
{
return NULL;
}
mskarr_set(pool->flags, index);
return (uint8_t *)pool->buffer + index * pool->size;
}
void vsfpool_free(struct vsfpool_t *pool, void *buffer)
{
int index = ((uint8_t *)buffer - (uint8_t *)pool->buffer) / pool->size;
if (index < pool->num)
{
mskarr_clr(pool->flags, index);
}
}
应用代码:
有兴趣的可以先想想这个可以怎么用,我之后公布
忘了说了,这个代码有BUG的,看谁能找粗来
公布示例代码了,分别是声明,初始化,分配,释放:
VSFPOOL_DEFINE(vsfip_buffer_pool, struct vsfip_buffer_t, VSFIP_CFG_IPBUF_NUM);
VSFPOOL_INIT(&vsfip_buffer_pool, struct vsfip_buffer_t, VSFIP_CFG_IPBUF_NUM);
buffer = VSFPOOL_ALLOC(&vsfip_buffer_pool, struct vsfip_buffer_t);
VSFPOOL_FREE(&vsfip_buffer_pool, buffer);
BUG的话,在vsfpool_free里。
|