import
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
#ifndef INCLUDED_POOL_H
|
||||
#define INCLUDED_POOL_H
|
||||
|
||||
#ifndef INCLUDED_OS_TYPES_H
|
||||
#include <os_types.h>
|
||||
#endif /*INCLUDED_OS_TYPES_H*/
|
||||
|
||||
#ifndef INCLUDED_OS_COMPILER_H
|
||||
#include <os_compiler.h>
|
||||
#endif /*INCLUDED_OS_COMPILER_H*/
|
||||
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------------------------ */
|
||||
/* https://www.gingerbill.org/article/2019/02/16/memory-allocation-strategies-004/ */
|
||||
|
||||
typedef struct pool_link_s {
|
||||
struct pool_link_s* next;
|
||||
}pool_link_t;
|
||||
|
||||
typedef struct {
|
||||
pool_link_t* free_list_p; /* 对象内存链表,每个节点指向一个对象内存地址 */
|
||||
os_size_t obj_size; /* 每个对象的大小 */
|
||||
os_size_t capacity; /* 池中最大能分配的对象数量 */
|
||||
os_size_t count; /* 已分配的对象数量 */
|
||||
}pool_t;
|
||||
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------------------------ */
|
||||
/* */
|
||||
|
||||
void pool_add_block(pool_t* self, void* block, os_size_t block_size);
|
||||
|
||||
/*
|
||||
* pool_t pool;
|
||||
* uint8_t block1[512];
|
||||
* uint8_t block2[1024];
|
||||
* uint8_t block3[256];
|
||||
*
|
||||
* pool_init(&pool, 16);
|
||||
* pool_add_block(&pool, block1, 512);
|
||||
* pool_add_block(&pool, block2, 1024);
|
||||
* pool_add_block(&pool, block3, 256);
|
||||
*
|
||||
* void* obj1 = pool_alloc(&pool);
|
||||
* ...
|
||||
* pool_free(&pool, obj1);
|
||||
*
|
||||
*/
|
||||
|
||||
OS_STATIC_FORCE_INLINE
|
||||
void pool_init(pool_t* self, os_size_t obj_size){
|
||||
self->free_list_p = 0;
|
||||
self->obj_size = obj_size;
|
||||
self->count = 0;
|
||||
self->capacity = 0;
|
||||
}
|
||||
|
||||
OS_STATIC_FORCE_INLINE
|
||||
void* pool_alloc(pool_t* self){
|
||||
if(!self->free_list_p){
|
||||
return NULL;
|
||||
}
|
||||
pool_link_t* p = self->free_list_p;
|
||||
self->free_list_p = p->next;
|
||||
self->count++;
|
||||
return p;
|
||||
}
|
||||
|
||||
OS_STATIC_FORCE_INLINE
|
||||
void pool_free(pool_t* self, void* obj){
|
||||
pool_link_t* p_link = (pool_link_t*) obj;
|
||||
p_link->next = self->free_list_p;
|
||||
self->free_list_p = p_link;
|
||||
self->count--;
|
||||
}
|
||||
|
||||
|
||||
#endif /*INCLUDED_POOL_H*/
|
||||
Reference in New Issue
Block a user