Refresh both AGENTS guides and clarify module purpose, usage, ownership, threading, return values and wire formats in headers. Remove the unused timeout_heap freed_count field and unimplemented getter.
56 lines
3.1 KiB
C
56 lines
3.1 KiB
C
/* memory_pool — повторное использование блоков фиксированного размера в одном потоке.
|
|
* init создаёт пустой пул; alloc выделяет блок по требованию или берёт свободный и обнуляет payload.
|
|
* free проверяет защитный хвост и возвращает не более MEMORY_POOL_MAX_FREE блоков в кеш.
|
|
* object_size должен вмещать void*: свободный блок хранит next в начале payload.
|
|
* Перед destroy вернуть все выданные блоки: destroy освобождает только кеш и сам пул.
|
|
* name заимствован до destroy; блок возвращать только своему пулу, внутренней синхронизации нет. */
|
|
#ifndef MEMORY_POOL_H
|
|
#define MEMORY_POOL_H
|
|
|
|
#ifdef __cplusplus
|
|
extern "C" {
|
|
#endif
|
|
|
|
|
|
#include <stddef.h>
|
|
#include "debug_config.h"
|
|
|
|
#define MEMORY_POOL_MAX_FREE 64
|
|
|
|
#define XSTR(s) STR(s)
|
|
#define STR(s) #s
|
|
#define PLOCATION __FILE__ ":" XSTR(__LINE__) "[POOL]"
|
|
|
|
struct memory_pool {
|
|
void* free_head; // Голова linked list свободных блоков (next хранится в начале каждого блока)
|
|
int free_count; // Количество свободных блоков
|
|
size_t object_size; // Размер объектов в пуле (пользовательские данные)
|
|
size_t allocations; // Общее количество аллокаций (включая новые malloc)
|
|
size_t reuse_count; // Количество повторных использований из пула
|
|
uint8_t alloc_tag_counter; // монотонный счётчик для детекции double-free (1 байт)
|
|
const char* name; // Имя пула для диагностики (напр. "data_pool", "pkt_pool")
|
|
};
|
|
|
|
// сам пул:
|
|
// если используем с элементами ll_queue то не забываем что к object_size надо прибавить sizeof(struct ll_entry)
|
|
struct memory_pool* memory_pool_init(size_t object_size, const char* name);
|
|
void memory_pool_destroy(struct memory_pool* pool);
|
|
|
|
// элементы пула:
|
|
void* memory_pool_alloc_impl(struct memory_pool* pool, const char* location);
|
|
void memory_pool_free_impl(struct memory_pool* pool, void* obj, const char* location);
|
|
void memory_pool_get_stats(struct memory_pool* pool, size_t* allocations, size_t* reuse_count);
|
|
size_t memory_pool_get_total_free_blocks(void);
|
|
|
|
#define memory_pool_alloc(pool) memory_pool_alloc_impl(pool, PLOCATION)
|
|
#define memory_pool_free(pool, obj) memory_pool_free_impl(pool, obj, PLOCATION)
|
|
|
|
/* Проверяет присутствие в кеше свободных блоков; не определяет состояние уже освобождённого через u_free блока. */
|
|
int memory_pool_is_freed(struct memory_pool* pool, void* obj);
|
|
|
|
|
|
#ifdef __cplusplus
|
|
}
|
|
#endif
|
|
#endif // MEMORY_POOL_H
|