自实现内存池:按大小分桶,8bit跨度,支持释放。
resp协议pipline测试。
This commit is contained in:
67
memory/mempool.h
Normal file
67
memory/mempool.h
Normal file
@@ -0,0 +1,67 @@
|
||||
#ifndef __MEMORY_POOL_H__
|
||||
#define __MEMORY_POOL_H__
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MEMPOOL_PAGE_SIZE 4096
|
||||
#define MEMPOOL_BLOCK_MAX_SIZE 512
|
||||
#define MEMPOOL_ALIGNMENT 8
|
||||
#define MEMPOOL_NUM_CLASSES (MEMPOOL_BLOCK_MAX_SIZE / MEMPOOL_ALIGNMENT)
|
||||
#define MEMPOOL_CACHE_PAGE 2
|
||||
|
||||
typedef struct mp_page_s mp_page_t;
|
||||
typedef struct mp_bucket_s mp_bucket_t;
|
||||
typedef struct mp_pool_s mp_pool_t;
|
||||
typedef struct mp_large_s mp_large_t;
|
||||
|
||||
typedef enum{
|
||||
MEMPOOL_INVALID_INPUT = -1,
|
||||
MEMPOOL_MALLOC_ERROR = -2,
|
||||
MEMPOOL_DOUBLE_FREE = -3,
|
||||
}mp_err_t;
|
||||
|
||||
struct mp_page_s{
|
||||
mp_bucket_t *owner;
|
||||
|
||||
mp_page_t *next;
|
||||
mp_page_t *prev;
|
||||
|
||||
void *free_list;
|
||||
|
||||
uint16_t free_count;
|
||||
uint16_t capacity;
|
||||
|
||||
uint64_t bitmap[8]; // 最多支持 512 个块 (64*8)
|
||||
};
|
||||
|
||||
struct mp_bucket_s{
|
||||
size_t block_size; // 桶中块大小
|
||||
uint32_t page_count; // 桶中页数
|
||||
uint32_t empty_count; // 空闲页数
|
||||
|
||||
mp_page_t *empty_pages; // 完全空闲page
|
||||
mp_page_t *partial_pages; // 空闲page
|
||||
mp_page_t *full_pages; // 满page
|
||||
};
|
||||
|
||||
struct mp_large_s{
|
||||
mp_large_t *next;
|
||||
mp_large_t *prev;
|
||||
};
|
||||
|
||||
struct mp_pool_s{
|
||||
mp_bucket_t buckets[MEMPOOL_NUM_CLASSES];
|
||||
|
||||
mp_large_t *large_list;
|
||||
};
|
||||
|
||||
int mp_create(mp_pool_t *pool);
|
||||
int mp_destroy(mp_pool_t *pool);
|
||||
|
||||
void *mp_alloc(mp_pool_t *pool, size_t size);
|
||||
int mp_free(mp_pool_t *pool, void *ptr);
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user